In this article we will going to look some very useful built-in functions that will always come handly in your python journey,
these functions will save you writing extra lines of code,
We will going to understand the defination and look some useful use-cases for each built-in function.
We will going to go through the following built-in functions :-
- map()
- filter()
- reduce()
- zip()
- enumerate()
- all()
- any()
1. map()
map() is a built-in Python function that takes in two or more arguments: a function and one or more iterables, in the form:
Syntax :- *map(callable, iterable)map() returns an iterator - that is, map() returns a special object that yields one result at a time as needed.
if you're not fimiliar with iterator :-
refer to this post :- iterator,iterable in pythonfor n size of input , it will return n size output
let's see some example of map()
Task :- convert list of string integer to to int
Example:-
lst_of_str_ints = ['1','2','3','4','5','6','7','8','9','10']
print("list of str ints :- ",lst_of_str_ints)
lst_of_ints = list(map(int, lst_of_str_ints))
print("list of ints :- ",lst_of_ints)
Output :-
list of str ints :- ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
list of ints :- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
we passed int object as first argument in the map function, second argument is the list_of_str_int, in this example
the iterator iterate each element at a time and map it to the corresponding callable argument int() passed as first argument,
then after iterating over all the elements, the map() function returns a map object will can then be casted to iterable like
(list,tuple,set).
we can perform the same task using lambda function:-
Example:-
lst_of_str_ints = ['1','2','3','4','5','6','7','8','9','10']
print("list of str ints :- ",lst_of_str_ints)
lst_of_ints = list(map(lambda x:int(x), lst_of_str_ints))
print("list of ints :- ",lst_of_ints)
Output :-
list of str ints :- ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
list of ints :- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example :-
Task :- we will convert temprature from celsius to fahrenheit
temps_in_celsius = [0, 22.5, 40, 100]
print("temprature in celsius :-",temps_in_celsius)
temps_in_fahrenheit = list(map(lambda celsius : (9/5)*celsius + 32, temps_in_celsius))
print("temprature in fahrenheit :-",temps_in_fahrenheit)
Output :-
temprature in celsius :- [0, 22.5, 40, 100]
temprature in fahrenheit :- [32.0, 72.5, 104.0, 212.0]
In the above example we converted list of temperature in celsius to "temprature in fahrenheit"
Example :-
Task :- capitalize each name in a list to uppercase
names = ['Ram','Shyam','Abhiansh','Raven','Marcus']
print("Original list :-",names)
upper_cased_names = list(map(lambda x : x.upper(), names))
print("Upper case name :-",upper_cased_names)
Output :-
Original list :- ['Ram', 'Shyam', 'Abhiansh', 'Raven', 'Marcus']
Upper case name :- ['RAM', 'SHYAM', 'ABHIANSH', 'RAVEN', 'MARCUS']
2. filter()
filter(function, iterable)( offers a efficient way to filter out all the elements of an iterable, based on if a condition evaluates to treu
**Syntax :- *filter(callable, iterable)*It takes first argument as function which evaluates to some boolean condition (True or False), second argument as iterable
The element will only be included if the function return **
for n size of input , it will return n-m size output
where m is the no. of element for which the function evaluates to False
let's see some example of filter()
Task :- fitler ints from a list of object of various type i.e. (float,string,lst,...)
Example :-
lst = [12, 43.42, 'hello', [1,3,4], 54,92, (1,2), 12.22, 9]
print("Orignal list of object without filteration :- ",lst)
lst_of_ints = list(filter(lambda x:type(x)== int, lst))
print("Updated list of ints :- ",lst_of_ints)
Output :-
Orignal list of object without filteration :- [12, 43.42, 'hello', [1, 3, 4], 54, 92, (1, 2), 12.22, 9]
Updated list of ints :- [12, 54, 92, 9]
In the above example we have filtered ints from a list of objects of different type, we used the same approch as in the previous example, but not here we're using a function which evaluates to two condition ,i.e., if the type of object is int then it returning True, and that element get included in the result list , Otherwise if the type in not int then it returning False , means item will not be included in the result list
let's see some other example :-
Task :- filter even integer from a list of integers
Example :-
list_of_ints = [1,2,3,4,5,6,7,8,9,10]
print("Orignal list of ints :- ",list_of_ints)
list_of_even_ints = list(filter(lambda x: x % 2 ==0, list_of_ints))
print("Updated list of only even ints :- ",list_of_even_ints)
Output :-
Orignal list of ints :- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Updated list of only even ints :- [2, 4, 6, 8, 10]
In the above example we filtered list of even integer from a list of integers.
Task :- we have a list of random emails, so of which are valid and some are invalid , we have to filter out only valid emails
Example :-
import re
list_of_emails = ['nullchar@aol.com',
'salesgeek@yahoo.com',
'luebkehotmail.com',
'fmergeslive.com',
'jonathan@outlook.com',
'lydia@gmail.com',
'grdschl@comcast.net',
'catalogsbcglobal.net',
'glenz@outlook.com',
'cumarana@outlook.com',
'rsteinericloud.com',
'mosses@mac.com']
email_regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
print("Orignal list of emails :- ",list_of_emails,"\n")
valid_emails = list(filter(lambda email:re.match(email_regex, email), list_of_emails))
print("Updated list of valid emails :- ",valid_emails)
Output :-
Orignal list of emails :- ['nullchar@aol.com', 'salesgeek@yahoo.com', 'luebkehotmail.com', 'fmergeslive.com', 'jonathan@outlook.com', 'lydia@gmail.com', 'grdschl@comcast.net', 'catalogsbcglobal.net', 'glenz@outlook.com', 'cumarana@outlook.com', 'rsteinericloud.com', 'mosses@mac.com']
Updated list of valid emails :- ['nullchar@aol.com', 'salesgeek@yahoo.com', 'jonathan@outlook.com', 'lydia@gmail.com', 'grdschl@comcast.net', 'glenz@outlook.com', 'cumarana@outlook.com', 'mosses@mac.com']
In the above example we make use of re regex module to match if the email is valid or not using the regular expression in email_regex variable, and after iterating over each element at matching it to the email_regex we get a list of valid emails
3. reduce()
- The function reduce(function, sequence) continually applies the function to the sequence. It then returns a single value. Syntax :- *reduce(callable, iterable)
i.e., If seq = [ s1, s2, s3, ... , sn ], calling reduce(function, sequence) works like this:
- At first the first two elements of seq will be applied to function, i.e. func(s1,s2)
- The list on which reduce() works looks now like this: [ function(s1, s2), s3, ... , sn ]
- In the next step the function will be applied on the previous result and the third element of the list, i.e. function(function(s1, s2),s3)
- The list looks like this now: [ function(function(s1, s2),s3), ... , sn ]
- It continues like this until just one element is left and return this element as the result of reduce()
let's see some example of reduce()
Task :- reduce a list of int to a single integer using + operator
Example :-
from functools import reduce
lst =[47,11,42,13]
print("Original list :- ",lst)
print("reduced value :- ",reduce(lambda x,y: x+y,lst))
Output :-
Original list :- [47, 11, 42, 13]
reduced value :- 113
let me explain what is going on in the above example
45 11 42 13
\ / / /
\ / / /
58 / /
\ / /
\ / /
100 /
\ /
\ /
\ /
113
numbers at index 0 and 1 first added
then their sum added with value at index 3
then their sum added with value at index 4
then after completing the sequence
we the reduced value :- 113
let's see one more example of reduce
Task :- reduce a list of int to a single integer using * operator
from functools import reduce
lst =[47,11,42,13]
print("Original list :- ",lst)
print("reduced value :- ",reduce(lambda x,y: x*y,lst))
Output :-
Original list :- [47, 11, 42, 13]
reduced value :- 282282
The visual that i have demostrated in the previous example ,in this example the same process going , but this time using x operator.
4. zip()
The function zip() makes an iterator that combines elements from each of the iterables
Syntax :- zip(iter1, iter2, iter3, iter4....)zip() function return zip object which iterate over a list of tuples where tuples size is equal to the no. of list passed in the zip() function.
The iterator stops when the shortest input iterable is exhausted
i.e it will return list of tuples of size equal to the length of (minimum size *iterable among all the iterables passed in the zip() function)*
let's see some example of zip()
Task :- we will combine user firstname,lastname,hometown using
zip() function
Example :-
first_names = ['ram','shyam','ajay','bipin','manoj','alex']
print("list of first names :- ", first_names,"\n")
last_names = ['gupta','tiwari','yadav','rawat','desai','khan','raven']
print("list of first names :- ", last_names,"\n")
home_towns = ['ayodhya','vrindavan','bihar','jhnasi','boston','delhi','lanka']
print("list of hometowns :-" , home_towns,"\n")
persons_info = list(zip(first_names,last_names,home_towns))
print("data after using zip() function :-",persons_info)
Output :-
list of first names :- ['ram', 'shyam', 'ajay', 'bipin', 'manoj', 'alex']
list of first names :- ['gupta', 'tiwari', 'yadav', 'rawat', 'desai', 'khan', 'raven']
list of hometowns :- ['ayodhya', 'vrindavan', 'bihar', 'jhnasi', 'boston', 'delhi', 'lanka']
data after using zip() function :- [('ram', 'gupta', 'ayodhya'), ('shyam', 'tiwari', 'vrindavan'), ('ajay', 'yadav', 'bihar'), ('bipin', 'rawat', 'jhnasi'), ('manoj', 'desai', 'boston'), ('alex', 'khan', 'delhi')]
In the above example we have combined inforation from three iterable (firstnames,lastnames,hometowns) into list of tuples with information combined from all three iterables.
also notice that,
it has returned a list of tuples of size equal to the length of (minimum size *iterable among all the iterables passed in the zip() function)
i.e
* first_names list has length of 6
* last_names list has length of 6
* home_town list has length of 7
5. enumerate()
The function enumerate() return an iterates to a list of tuples , where first element of each tuple is it's corresponding index (by default is 0) and second element is the value at store at the index
Syntax :- enumerate(iterable, start)the second argument start denotes from where the index start
i.e., if start = 4 then [(value1,4), (value2,5), (value3,6)...]
let's us take an example with start argument and without start arguement
Task :- without start argument
Example :-
names = ['ram','shyam','ajay','bipin','manoj','alex']
names_with_indexes = list(enumerate(names))
for name in names_with_indexes:
print(name)
Output :-
(0, 'ram')
(1, 'shyam')
(2, 'ajay')
(3, 'bipin')
(4, 'manoj')
(5, 'alex')
Task :- with start argument
Example :-
names = ['ram','shyam','ajay','bipin','manoj','alex']
names_with_indexes = list(enumerate(names, 4))
for name in names_with_indexes:
print(name)
Output :-
(4, 'ram')
(5, 'shyam')
(6, 'ajay')
(7, 'bipin')
(8, 'manoj')
(9, 'alex')
you can see the difference in the above two examples
6. all()
all() are built-in functions that allow us to conveniently check for boolean matching in an iterable.
Syntax :- all(iterable)all() will return True if all elements in an iterable are True.
let's understand with examples
Example :-
lst = [True,True,False,True]
print(all(lst))
Output :-
False
Since element at index 2 is false , all() returned False
Example
lst = [True,True,True,True]
print(all(lst))
Output :-
True
Now the result is True
Example
lst = [True,[],[1,2,3],True]
print(all(lst))
Output :-
False
if any one coufused why the result is False, there is a concept of Truthy and Falsy in python.
here is a good example your can check Truthy and Falsy in python
7. any()
any() are built-in functions that allow us to conveniently check for boolean matching in an iterable.
Syntax :- any(iterable)any() will return True if any elements in an iterable are True.
let's understand with examples
Example :-
lst = [True,False,False,False]
print(any(lst))
Output :-
True
Since element at index 0 is True, any() returned True
Example
lst = [False,False,False,False]
print(any(lst))
Output :-
False
Now the result is False
Example
lst = [(),[],[1,2,3],False]
print(any(lst))
Output :-
True
Now the result is true because at index 2, there is a list of size greater than 0 , which is a Truthy value.
with this example we have come to an end,
we have covered various useful built-in functions
which are very useful in certain scenarios
Hope you all have learned some useful stuff today. :-)
Top comments (3)
Hi
I think the output should be False here.
thanks for such a fine overview.
I corrected the output
By the way thanks
For pointing out the mistake 👍
No problem.
Changing the example would have been better in my opinion. to make it all True.