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.

Syntax: zip(iterator1, iterator2, ...)
Exemple: languages = ['Python', 'Java', 'C++', 'Php', 'Julia']
                rating = [46, 30, 12, 8, 4]
                zip_lang = zip(languages, rating)
                # Let convert this zip_lang into a list then print it out
               print(list(zip_lang))


Thanks.

Comments

Popular posts from this blog

Extracting Dates From Medical Data

HISTOIRE DE MINEMBWE ET SES AUTOCHTONES

Variables, expressions, and statements in Python