How to use zip() function in Python
In this article, we will learn how to use the zip() function in Python.
The function takes multiple iterators as arguments i.e iterator objects the will be joined together.
The function returns a zip object. It is an iterator in the form of a tuple.
Python- zip() function
- iterator1, iterator2,..: The objects that will be joined together using the function.
Example of zip() function
In this example, we have 2 two tuples. Both the tuples contain an equal number of items. The function returns a tuple.
first_name = ("Barack", "George", "Bill") last_name = ("Obama", "Bush", "Clinton") answer= zip(first_name, last_name) print(tuple(answer))
(('Barack', 'Obama'), ('George', 'Bush'), ('Bill', 'Clinton'))
Let’s see another example…
In this example, we again have 2 tuples. But one tuple contains more items. The function ignores the extra item since the length of the new iterator is decided by the iterator which contains the least number of items.
first_name = ("Monica", "Joey", "Phoebe", "Chandler", "Rachel", "Ross") last_name = ("Geller", "Tribbiani", "Buffay", "Bing", "Greene") answer= zip(first_name, last_name) print(tuple(answer))
(('Monica', 'Geller'), ('Joey', 'Tribbiani'), ('Phoebe', 'Buffay'), ('Chandler', 'Bing'), ('Rachel', 'Greene'))
Applications of zip() function
- It can be used to create a database.
- It can be used to create a scorecard for given data.
- It can be used for mapping groups of data.
These applications can be demonstrated using an example.
In this example, we’ll create a scorecard for a game played by a group of four people.
players = [ "Penny", "Sheldon", "Raj", "Amy"] # initializing their scores scores = [20, 15, 17, 28] for p, s in zip(players, scores): print ("Player : %s Score : %d" %(p, s))
Player : Penny Score : 20 Player : Sheldon Score : 15 Player : Raj Score : 17 Player : Amy Score : 28