1.21. builtin functions
Contents
Note
Click here to download the full example code or to run this example in your browser via Binder
1.21. builtin functions#
This lesson shows the usage of builtin functions available in python. These functions are available in python without importing any module. These are not all the builtin functions but only those which are used frequently.
Important
This lesson is still under development.
slice#
[1, 2]
print(a[slice(2, 8)])
[3, 4, 5, 6, 7, 8]
print(a[slice(2, 8, 2)])
[3, 5, 7]
Th
is is
i s
(1, 2)
(3, 4, 5, 6, 7, 8)
(3, 5, 7)
a = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
# print(a[slice(2)])
Indeed, any python object which can be sliced using [] operator, can also be sliced
using slice function.
Although, [] operator and slice function look similar however they differ in
their behavior. [] operator returns the values whereas slice function returns
a slice object. Moreover, slice function is more readable and flexible.
zip#
zip is used to iterate over two or more than two sequences.
1 11
2 12
3 13
any#
False
True
all#
True
False
True
False
Question:
What is the type of the output returned by any and all functions?
sorted#
a
b
c
a
b
c
1
3
5
10.0
reversed#
c
b
a
enumerate#
0 a
1 b
2 c
Question:
What will be the output of the following code?
Question:
Consider the following list
dob_years = ['1334', '1506', '1542', '1700s', '1935']
Now modify the for loop in the previous example to also iterate over
dob_years list along with names and years.
map#
Suppose we have function which takes an input and returns square of it
def square(x):
return x**2
Now if we want to call this function on several values, we can make a list of all the values on which we want to call it
vals = [1,2,3,4,5]
and then we can call this function in a loss
1
4
9
16
25
An alternative to calling the function in an explicit for loop
is to make use of map function.
The map function returns an iterator which we can be converted into a list
print(type(mapper))
<class 'map'>
True
We can extract all values from iterator by calling list method on it.
list(mapper)
[1, 4, 9, 16, 25]
we can also provide any builtin function as first argument to map
list(map(float, vals))
[1.0, 2.0, 3.0, 4.0, 5.0]
we can also use map with functions which take multiple input input arguments.
[1, 4, 27, 256]
- Map has several advantages over an explicit for loop e.g
It is fast since it is written in C
It is memory efficient as it returns an iterator
Question:
Convert the years in following list from Hijri to Gregorian 1 calenden using map function
hijri_years = [40, 50, 61, 95, 114, 148, 183, 203, 220, 254, 260]
Total running time of the script: ( 0 minutes 0.010 seconds)