How to use map(), zip() functions in Python
Python map() function
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Syntax: map(function, iterable)
Parameters:
- function is a function to which map passes each element of Iterable
- iterable is any variable containing more that one values, this variable can be a list(), Tuple() or Dictionary().
Exemple: The code below will convert all elements in a given list into uppercase.
def myfunction(mylist):
return mylist.upper()
mylist = ['python', 'java', 'kotlin', 'ruby']
my_upper_list = map(myfunction, mylist)
print(list(my_upper_list)) # ['PYTHON', 'JAVA', 'KOTLIN', 'RUBY']
We can change this code using lambda into a simple way like this:
res = map(lambda element: element.upper(), mylist)
print(list(res))
Python zip() function
The zip()
function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
Comments
Post a Comment