Python Built-in Functions
Phython has a number of built-in functions, we use in every .py although we are not aware of it. That is the full list of built-in functions.
We already know some of them. Now I will try some I may be need to use later. Let’s have a start with help function.
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
As you see, print function is another built-in function, every day used but some may noticed late it has “sep” and “end” argumets. There may be another function which we don’t know it has useful arguments. So we can use help function to get info about it.
Another useful function is id function. It return a unique number for an object or a variable that we passed as an argument. Thanks to this unique number, we can understand is this object or variable changed or remained the same.
>>> a = 10
>>> id(a)
2033577951760
>>> a = 20
>>> id(a)
2033577952080
>>> a_dict = {"a":3, "b":5}
>>> id(a_dict)
2033579243840
>>> a_dict["a"] = 6
>>> id(a_dict)
2033579243840
>>> a_list = [3,5,7]
>>> id(a_list)
2033583404544
>>> a_list.append(9)
>>> id(a_list)
2033583404544
As you see in the example above, when lists or dictionaries change, their ids remain the same.
And bool function. If an object we passed as an argument to this function, is not empty or zero, it returns True, otherwise returns False.
>>> s = "test"
>>> bool(s)
True
>>> a = 10
>>> bool(a)
True
>>> a_list = [3,5]
>>> bool(a_list)
True
>>> a_dict = { "a":1
... , "b":2}
>>> bool(a_dict)
True
>>>
>>> s = ""
>>> bool(s)
False
>>> a = 0
>>> bool(a)
False
>>> a = -1
>>> bool(a)
True
>>> a_list = []
>>> bool(a_list)
False
>>> a_dict = { }
>>> bool(a_dict)
False
Sorted function. It sorts items alphabetically. But it’s not useful for sorting lists whose items are both with capital letters and small letters. Because, it takes reference ASCI table. Another awkwardness is sorting items includes numbers after some text like abc_10 and abc_5.
>>> my_set = set(f"a_{x}" for x in range(1,8))
>>> my_set
{'a_3', 'a_5', 'a_1', 'a_7', 'a_4', 'a_2', 'a_6'}
>>> sorted(my_set)
['a_1', 'a_2', 'a_3', 'a_4', 'a_5', 'a_6', 'a_7']
>>> my_set = set(f"a_{x}" for x in range(7,15))
>>> sorted(my_set)
['a_10', 'a_11', 'a_12', 'a_13', 'a_14', 'a_7', 'a_8', 'a_9']
Another function is map. Let’s assume we have a function takes an argument. But we have list of arguments to pass this function and want to get the results. Thanks to map function, we can pass our argument list to a function and get the results. Our function is factorial and let’s calculate factorials of my list of numbers.
There is also another example that includes a functions takes a str and capitalizes the str. We will get VLAN names as capital letters.
>>> def factorial(x):
... return 1 if x == 1 else x * factorial(x-1)
...
>>> factorial(5)
120
>>> my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_map = map(factorial, my_numbers)
>>> my_map
<map object at 0x00000120CF2FAEC0>
>>> list(my_map)
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
>>> vlans = ["vlan_1","vlan_3","data","server_reject","guest"]
>>> upper_str = lambda s: s.upper()
>>> VLANS = list(map(upper_str, vlans))
>>> VLANS
['VLAN_1', 'VLAN_3', 'DATA', 'SERVER_REJECT', 'GUEST']
Filter function. We have a set of data and we want to filter this data with the help of a function. Filter function takes this function and the data as arguments. Our function should return True or False, so filter function can decide is the an item should be filtered or not.
In our example below, we have list of devices which types are dictionary. We are checking for a dictionary key to filter.
>>> my_devices = [{ "hostname":"r1","device_type":"cisco_ios"},
... {"hostname":"r2", "device_type":"cisco_ios"},
... {"hostname":"r3", "device_type":"juniper"},
... {"hostname":"sw1", "device_type":"arista"}]
>>> is_cisco = lambda d: True if d["device_type"]=="cisco_ios" else False
>>> my_cisco_devices = list(filter(is_cisco, my_devices))
>>> my_cisco_devices
[{'hostname': 'r1', 'device_type': 'cisco_ios'}, {'hostname': 'r2', 'device_type': 'cisco_ios'}]
Reduce function. It’s not in build-in function 🙂 But it worth showing here. It doesn’t returns a result set. It uses all the set and produce a result.
>>> from functools import reduce
>>> def my_concat(a,b):
... return a+b
...
>>> ss = ["This","is","a","list"]
>>> cc = reduce(my_concat, ss)
>>> cc
'Thisisalist'
>>> numbers = [5, 10, 30, 400, 25, 13, 1000, 80, 5001]
>>> max = reduce(lambda x,y: x if x>y else y, numbers)
>>> max
5001
Built-in functions post ends here. But I will update this post for another useful functions.