Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Built-in Function

Back


Iterable Item

iter(object, sentinel)

print("\n--------- iter(object, sentinel) --------\n")

x_iter = iter(["apple", "banana", "cherry"])

print(next(x_iter))     # apple
print(next(x_iter))     # banana
print(next(x_iter))     # cherry
# print(next(x_iter))     # StopIteration

len(object)

print("\n--------- len(object) --------\n")

print(len(["apple", "banana", "cherry"]))  # 3
print(len("Hello"))  # 5

next(iterable, default)

print("\n--------- next(iterable, default) --------\n")

x_list = iter(["apple", "banana", "cherry"])
print(next(x_list, "end"))      # apple
print(next(x_list, "end"))      # banana
print(next(x_list, "end"))      # cherry
print(next(x_list, "end"))      # end
print(next(x_list, "end"))      # end

all(iterable)

print("\n--------- all(iterable) --------\n")

# string list
print(all(["none", "str", "list"]))  # True
print(all(["", "str", "list"]))  # False

# num list
print(all([1, 1, 1]))  # True
print(all([0, 1, 1]))  # False

# boolean list
print(all([True, True, True]))  # True
print(all([False, True, True]))  # False

# set
print(all({-1, 1, 2}))  # True
print(all({0, 1, 2}))  # False

# dict, check all keys
print(all({1: "Apple", 2: "Orange"}))  # True
print(all({0: "Apple", 1: "Orange"}))  # False

any(iterable)

print("\n--------- any(iterable) --------\n")

# false object
print(any([False, 0, "", [], (), set(), dict()]))  # False

# string list
print(any(["", "str", ""]))  # True
print(any(["", "", ""]))  # False

# num list
print(any([0, 1, 0]))  # True
print(any([0, 0, 0]))  # False

# boolean list
print(any([False, True, False]))  # True
print(any([False, False, False]))  # False

# set
print(any({0, 1}))  # True
print(any({0, None, ""}))  # False

# dict, check any keys
print(any({0: "Apple", 1: "Orange"}))  # True
print(any({0: "Apple"}))  # False

range(start, stop, step)

print("\n--------- range(start, stop, step) --------\n")

for num in range(3):
    print(num)
# 0
# 1
# 2


for num in range(1, 4):
    print(num)
# 1
# 2
# 3

for num in range(1, 4, 2):
    print(num)
# 1
# 3

for num in range(3, 0, -1):
    print(num)
# 3
# 2
# 1

enumerate(iterable, start)

print("\n--------- enumerate(iterable, start) --------\n")

x_list = ('apple', 'banana', 'cherry')

for index, itm in enumerate(x_list):
    print(index, itm)
# 0 apple
# 1 banana
# 2 cherry

for index, itm in enumerate(x_list, 10):
    print(index, itm)
# 10 apple
# 11 banana

filter(function, iterable)

print("\n--------- filter(object, globals, locals) --------\n")

ages = [5, 12, 17, 18, 24, 32]


def over18(x):
    if x < 18:
        return False
    else:
        return True


print(type(filter(over18, ages)))   # <class 'filter'>

[print(itm) for itm in filter(over18, ages)]
# 18
# 24
# 32

map(function, iterables)

print("\n--------- map(function, iterables) --------\n")


def xFunc(n):
    return len(n)


mObj = map(xFunc, ('apple', 'banana', 'cherry'))
print(type(mObj))  # <class 'map'>

print([itm for itm in mObj])   # [5, 6, 6]


def yFunc(a, b):
    return a + " " + b


mObj = map(yFunc, ('apple', 'banana', 'cherry'),
           ('orange', 'lemon', 'pineapple'))
print([itm for itm in mObj])
# ['apple orange', 'banana lemon', 'cherry pineapple']


zip([iterator])

print("\n--------- zip([iterator]) --------\n")

x_list = ("John", "Charles", "Mike")
y_list = ("Jenny", "Christy", "Monica")

print(type(zip(x_list, y_list)))    # <class 'zip'>

[print(x, y) for x, y in zip(x_list, y_list)]
# John Jenny
# Charles Christy
# Mike Monica

# shorter list decide the len
x_list = ("John", "Charles", "Mike")
y_list = ("Jenny", "Christy", "Monica", "Vicky")
[print(x, y) for x, y in zip(x_list, y_list)]
# John Jenny
# Charles Christy
# Mike Monica

slice(start, end, step)

print("\n--------- slice(start, end, step) --------\n")

nums = ("a", "b", "c", "d", "e", "f", "g", "h")
print(slice(2))  # slice(None, 2, None)
print(nums[slice(2)])  # ('a', 'b')

print(slice(3, 5))  # slice(3, 5, None)
print(nums[slice(3, 5)])  # ('d', 'e')

print(slice(0, 8, 3))  # slice(0, 8, 3)
print(nums[slice(0, 8, 3)])  # ('a', 'd', 'g')

reversed(sequence)

print("\n--------- reversed(sequence) --------\n")

x_list = [1, 3, 5, 4, 2]
y_list = reversed(x_list)

print(type(x_list))  # <class 'list'>
print(x_list)   # [1, 3, 5, 4, 2]

print(type(y_list))  # <class 'list_reverseiterator'>
print(y_list)   # <list_reverseiterator object at 0x000001B0634310D0>

for itm in y_list:
    print(itm)
# 2
# 4
# 5
# 3
# 1

sum(iterable, start)

print("\n--------- sum(iterable, start) --------\n")

nums = (1, 2, 3, 4, 5)
print(sum(nums))    # 15
print(sum(nums, 7))  # 22

Number Function

abs(n)

print("\n--------- abs(n) --------\n")

print(abs(0))   # 0
print(abs(-7.25))   # 7.25
print(abs(7.25))    # 7.25

round(number, digits)

print("\n--------- round(number, digits) --------\n")

print(round(5.76543))   # 6
print(round(5.76543, 2))   # 5.77

max()

print("\n--------- max() --------\n")

print(max(5, 10))   # 10
print(max("Mike", "John", "Vicky"))  # Vicky
print(max(1, 5, 3, 9))      # 9

min()

print("\n--------- min() --------\n")

print(min(5, 10))   # 5
print(min("Mike", "John", "Vicky"))  # John
print(min(1, 5, 3, 9))      # 1

pow(x, y, z)

print("\n--------- pow(x, y, z) --------\n")

print(pow(4, 3))    # 64
print(pow(4, 3, 5))    # 4

Data Type Function

bool(object)

print("\n--------- bool(object) --------\n")

print(bool(0))  # False
print(bool(""))  # False
print(bool([]))  # False
print(bool(()))  # False
print(bool({}))  # False
print(bool(None))  # False
print(bool(False))  # False

chr(number)

print("\n--------- chr(number) --------\n")

print(chr(13))  # Enter
print(chr(16))  # Shift
print(chr(17))  # Ctrl
print(chr(18))  # Alt
print(chr(27))  # ESC
print(chr(48))  # 0
print(chr(97))  # a

float(value)

print("\n--------- float(value) --------\n")

# num
print(float(3))  # 3.0
print(float(3.00000))  # 3.0

# str
print(float("3"))  # 3.0
print(type(float("3")))  # <class 'float'>
print(float("3.25"))  # 3.25
print(type(float("3.25")))  # <class 'float'>

# print(float(""))  # ValueError: could not convert string to float: ''

String Function

format(value, format)

Value Description
< Left aligns the result (within the available space)
> Right aligns the result (within the available space)
^ Center aligns the result (within the available space)
= Places the sign to the left most position
+ Use a plus sign to indicate if the result is positive or negative
- Use a minus sign for negative values only
` ` Use a leading space for positive numbers
, Use a comma as a thousand separator
_ Use a underscore as a thousand separator
b Binary format
c Converts the value into the corresponding unicode character
d Decimal format
e Scientific format, with a lower case e
E Scientific format, with an upper case E
f Fix point number format
F Fix point number format, upper case
g General format
G General format (using a upper case E for scientific notations)
o Octal format
x Hex format, lower case
X Hex format, upper case
n Number format
% Percentage format
print("\n--------- format(value, format) --------\n")

print(format(255, 'x'))  # ff
print(format(0.5, '%'))  # 50.000000%

input(prompt)

print("\n--------- input(prompt) --------\n")

name = input('Enter your name:\n')
print('Hello, ' + name)

Object Function

id(object)

print("\n--------- id(object) --------\n")

x_tp = ('apple', 'banana', 'cherry')
print(id(x_tp))     # 2332518031552

dir(object)

print("\n--------- dir(object) --------\n")


class Person:
    name = "John"
    age = 36
    country = "Norway"


[print(pop) for pop in dir(Person)]
# __class__
# __delattr__
# __dict__
# __dir__
# __doc__
# __eq__
# __format__
# __ge__
# __getattribute__
# __gt__
# __hash__
# __init__
# __init_subclass__
# __le__
# __lt__
# __module__
# __ne__
# __new__
# __reduce__
# __reduce_ex__
# __repr__
# __setattr__
# __sizeof__
# __str__
# __subclasshook__
# __weakref__
# age
# country
# name

vars(object)

print("\n--------- vars(object) --------\n")


class Person:
    name = "John"
    age = 36
    country = "norway"


[print(k, ":", v) for k, v in vars(Person).items()]
# __module__ : __main__
# name : John
# age : 36
# country : norway
# __dict__ : <attribute '__dict__' of 'Person' objects>
# __weakref__ : <attribute '__weakref__' of 'Person' objects>
# __doc__ : None


isinstance(object, type)

print("\n--------- isinstance(object, type) --------\n")

# int
print(isinstance(5, int))   # True

# a type tuple
print(isinstance("Hello", (float, int, str, list, dict, tuple)))  # True

# object


class xObj:
    name = "John"


obj = xObj()
print(isinstance(obj, xObj))    # True

issubclass(object, subclass)

print("\n--------- issubclass(object, subclass) --------\n")


class superObj:
    age = 36


class subObj(superObj):
    name = "John"
    age = superObj.age


print(issubclass(subObj, superObj))  # True

hasattr(object, attribute)

print("\n--------- hasattr(object, attribute) --------\n")


class Person:
    name = "John"
    age = 36
    country = "Norway"


print(hasattr(Person, 'age'))   # True
print(hasattr(Person, 'page'))   # False

getattr(object, attribute, default)

print("\n--------- getattr(object, attribute, default) --------\n")


class Person:
    name = "John"
    age = 36
    country = "Norway"


print(getattr(Person, 'age'))   # 36
print(getattr(Person, 'page', 'my message'))   # my message

setattr(object, attribute, value)

print("\n--------- setattr(object, attribute, value) --------\n")


class Person:
    name = "John"
    age = 36
    country = "Norway"


print(getattr(Person, 'age'))   # 36

setattr(Person, 'age', 40)
print(getattr(Person, 'age'))   # 40

delattr(object, attribute)

print("\n--------- delattr(object, attribute) --------\n")


class Person:
    name = "John"
    age = 36
    country = "Norway"


print(hasattr(Person, "age"))   # True

delattr(Person, 'age')
print(hasattr(Person, "age"))   # False

Code Function

eval(expression, globals, locals)

print("\n--------- eval(expression, globals, locals) --------\n")

x = 'print(55)'
eval(x) # 55

exec(object, globals, locals)

print("\n--------- exec(object, globals, locals) --------\n")

code = 'name = "John"\nprint(name)'
exec(code)  # John

File Function

open(file, mode)

Mode Description
r Read - Default value. Opens a file for reading, error if the file does not exist
a Append - Opens a file for appending, creates the file if it does not exist
w Write - Opens a file for writing, creates the file if it does not exist
x Create - Creates the specified file, returns an error if the file exist
Mode Description
t Text - Default value. Text mode
b Binary - Binary mode (e.g. images)
print("\n--------- open(file, mode) --------\n")

f = open("test.txt", "r")
print(f.read())
# fsdfsdfsdf
# sdfsdf
# dsf
# sdfsdff
# sdfsdfsdf

TOP