10 - Useful Functions
10 - Useful Functions
Useful functions
This section discusses the following functions:
• print
• range
• sorted
• enumerate
• zip
• all_any
• lambda
• map
• filter
print
Function print has been used many times, but its full syntax has not yet been discussed:
print(*items, sep=' ', end='\n', file=sys.stdout, flush=False)
Function print outputs all elements by separating them by their sep value and finishes
output with end value.
sep
Parameter sep controls which separator will be used between elements. By default, space
is used. You can change sep value to any other string:
print(1, 2, 3, sep='|') # 1|2|3
print(1, 2, 3, sep=f"\n{'-' * 10}\n")
'''
1
----------
2
----------
3
'''
items = [1, 2, 3, 4, 5]
print(*items, sep=', ') # 1, 2, 3, 4, 5
58
end
Parameter end controls which value will be displayed after all elements are printed. By
default, new line character is used. You can change end value to any other string:
print(1, 2, 3, end='\n' + '-' * 10)
'''
1 2 3
----------
'''
file
Parameter file controls where values of print function are displayed. The default
output is sys.stdout.
Python allows to pass to file as an argument any object with write(string) method.
f = open('result.txt', 'w')
for num in range(10):
print('Item {}'.format(num), file=f)
f.close()
range
Function range returns an immutable sequence of numbers as a range object. Function
syntax:
range(stop)
range(start, stop[, step])
Parameters of function:
• start - from what number the sequence begins. By default - 0
• stop - on which number the sequence of numbers ends. Mentioned number is not
included in range
• step - with what step numbers increase. By default
59
Function range can also generate descending sequences of numbers:
list(range(10, 0, -1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
list(range(10, 0, -2)) # [10, 8, 6, 4, 2]
The range object supports all operations that support sequences in Python, except
addition and multiplication.
nums = range(5) # range(0, 5)
3 in nums # True
nums[0] # 0
nums[-1] # 4
# Range supports slices:
nums[1:] # range(1, 5)
nums[:3] # range(0, 3)
len(nums) # 5
min(nums) # 0
max(nums) # 4
sorted
Function sorted returns a new sorted list that is obtained from an iterable object that has
been passed as an argument. Function also supports additional options that allow you to
control sorting.
The first aspect that is important to pay attention to - sorted returns a list. If you sort a list
of items, a new list is returned:
list_of_words = ['one', 'two', 'list', '', 'dict']
60
If you pass a dictionary to sorted the function will return sorted list of keys:
dict_for_sort = {
'id': 1,
'name': 'London',
'it_vlan': 320,,
'mngmt_vlan': 99,
'port': 'G1/0/11'
}
sorted(dict_for_sort)
'''
['id',
'it_vlan',
'mngmt_vlan',
'name',
'port',]
'''
reverse
The reverse flag allows you to control the sorting order. By default, sorting will be in
ascending order of items:
list_of_words = ['one', 'two', 'list', '', 'dict']
sorted(list_of_words)
# ['', 'dict', 'list', 'one', 'two']
sorted(list_of_words, reverse=True)
# ['two', 'one', 'list', 'dict', '']
key
With key option you can specify how to perform sorting. The key parameter expects
function by which the comparison should be performed.
sorted(list_of_words, key=len)
# ['', 'one', 'two', 'list', 'dict']
The key option can accept any functions, not only embedded ones. It is also convenient to
use anonymous lambda() function.
61
enumerate
Sometimes, when iterating objects in for loop, it is necessary not only to get object itself
but also its sequence number. This can be done by creating an additional variable that will
increase by one with each iteration. However, it is much more convenient to do this with
iterator enumerate.
Basic example:
list1 = ['str1', 'str2', 'str3']
enumerate can count not only from scratch but from any value that has been given to it
after object:
list1 = ['str1', 'str2', 'str3']
list(enumerate(list1, 100))
# [(100, 'str1'), (101, 'str2'), (102, 'str3')]
62
zip
zip function:
• sequences are passed to function
• zip returns an iterator with tuples in which n-tuple consists of n-elements of
sequences that have been passed as arguments
• for example, 10th tuple will contain 10th element of each of passed sequences
• if sequences with different lengths have been passed to input, they will all be cut
by the shortest sequence
• the order of elements is respected
list(zip(a, b, c))
# [(1, 10, 100), (2, 20, 200), (3, 30, 300)]
r1 = dict(zip(d_keys, d_values))
print(r1)
'''
{'IOS': '15.4',
'IP': '10.255.0.1',
'hostname': 'london_r1',
'location': '21 New Globe Walk',
'model': '4451',
'vendor': 'Cisco'}
'''
63
In example below there is a separate list which stores keys and a dictionary which stores
information about each device in form of list (to preserve order).
Collect them in dictionary with keys from list and information from dictionary data:
d_keys = ['hostname', 'location', 'vendor', 'model', 'IOS', 'IP']
data = {
'r1': ['london_r1', '21 New Globe Walk', 'Cisco', '4451',
'15.4', '10.255.0.1'],
'r2': ['london_r2', '21 New Globe Walk', 'Cisco', '4451',
'15.4', '10.255.0.2'],
'sw1': ['london_sw1', '21 New Globe Walk', 'Cisco', '3850',
'3.6.XE', '10.255.0.101']
}
london_co = {}
for k in data.keys():
london_co[k] = dict(zip(d_keys, data[k]))
print(london_co)
all
Function all returns True if all elements are true (or object is empty).
all([False, True, True]) # False
For example, it is possible to check that all octets in an IP address are numbers:
ip = '10.0.1.1'
any
Function any returns True if at least one element is true.
any([i.isdigit() for i in '10.1.1.a'.split('.')]) # True
64
Anonymous function (lambda expression)
In Python, lambda expression allows creation of anonymous functions - functions that are
not tied to a name.
Anonymous function:
• may contain only one expression
• can pass as many arguments as you want
Standard function:
def sum_arg(a, b): return a + b
Note that there is no return operator in lambda function definition because there can only
be one expression in this function that always returns a value and closes the function.
Function lambda is convenient to use in expressions where you need to write a small
function for data processing. For example, in sorted function you can use lambda
expression to specify sorting key:
list_of_tuples = [('IT_VLAN', 320),
('Mngmt_VLAN', 99),
('User_VLAN', 1010),
('DB_VLAN', 11)]
Function lambda is also useful in map and filter functions which will be discussed in
the following sections.
65
map
Function map applies function to each element of sequence and returns iterator with
result.
For example, map can be used to perform element transformations. Convert all strings to
uppercase:
list_of_words = ['one', 'two', 'list', '', 'dict']
list(map(str.upper, list_of_words))
# ['ONE', 'TWO', 'LIST', '', 'DICT']
Converting to numbers:
list_of_str = ['1', '2', '5', '10']
66
Convert all strings to uppercase:
list_of_words = ['one', 'two', 'list', '', 'dict']
[str.upper(word) for word in list_of_words]
# ['ONE', 'TWO', 'LIST', '', 'DICT']
String formatting:
vlans = [100, 110, 150, 200, 201, 202]
['vlan {}'.format(x) for x in vlans]
# ['vlan 100', 'vlan 110', 'vlan 150', 'vlan 200', 'vlan 201',
'vlan 202']
filter
Function filter() applies function to all sequence elements and returns an iterator with
those objects for which function has returned True.
fAs a rule, you can use list comprehension instead of filter. Examples
similar to those above in list comprehension version. Return only those
strings that contain numbers:ter(str.isdigit, list_of_strings)
# <filter at 0xb45eb1cc>
list(filter(str.isdigit, list_of_strings))
# ['100', '1', '50']
67
List comprehension instead of filter
As a rule, you can use list comprehension instead of filter.
Examples similar to those above in list comprehension version.
Odd/even numbers:
nums = [10, 111, 102, 213, 314, 515]
68