Try it here
Subscribe
Uses of zip function

Python zip() Function

python_zip()_function_

zip() is available in the built-in namespace. If you use dir() to inspect __builtins__, then you’ll see zip() at the end of the list.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.(source)

Python’s zip() function is defined as zip(*iterables). The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

>>> chars = ['A', 'B', 'C']
>>> ascis = [65, 66, 67]
>>> zipped = zip(chars, ascis)
>>> list(zipped)
[('A', 65), ('B', 66), ('C', 67)]
>>> 

If you’re working with sequences like lists, tuples, or strings, then your iterables are guaranteed to be evaluated from left to right. This means that the resulting list of tuples will take the form [(chars[0], ascis[0]), (chars[1], ascis[1]),..., (chars[n], ascis[n])]. However, for other types of iterables (like sets), you might see some weird results:

>>> set1 = {'A', 'B', 'C'}
>>> set2 = {65, 66, 67}
>>> list(zip(set1, set2))
[('C', 65), ('A', 66), ('B', 67)]
>>> 

In this example, set1 and set2 are set objects, which don’t keep their elements in any particular order. This means that the tuples returned by zip() will have elements that are paired up randomly. If you’re going to use the Python zip() function with unordered iterables like sets, then this is something to keep in mind.

Passing Arguments of Unequal Length

In these cases, the number of elements that zip() puts out will be equal to the length of the shortest iterable. The remaining elements in any longer iterables will be totally ignored by zip(), as you can see here:

>>> list(zip(range(5), range(20)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> 

itertools.zip_longest()

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.

If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile(). If not specified, fillvalue defaults to None.

>>> import itertools
>>> chars = ['A', 'B', 'C']
>>> ascis = [65, 66, 67]
>>> longest = range(5)
>>> zipped = itertools.zip_longest(chars, ascis, longest, fillvalue='$')
>>> list(zipped)
[('A', 65, 0), ('B', 66, 1), ('C', 67, 2), ('$', '$', 3), ('$', '$', 4)]
>>> 

zip() in Python 3 and 2

Python’s zip() function works differently in both versions of the language. In Python 2, zip() returns a list of tuples. The resulting list is truncated to the length of the shortest input iterable. If you call zip() with no arguments, then you get an empty list in return.

In Python 3, however, zip() returns an iterator. This object yields tuples on demand and can be traversed only once. The iteration ends with a StopIteration exception once the shortest input iterable is exhausted. If you supply no arguments to zip(), then the function returns an empty iterator.

If you regularly use Python 2, then note that using zip() with long input iterables can unintentionally consume a lot of memory. In these situations, consider using itertools.izip(*iterables) instead. This function creates an iterator that aggregates elements from each of the iterables. It produces the same effect as zip() in Python 3.

If you really need to write code that behaves the same way in both Python 2 and Python 3, then you can use a trick like the following:

try:
    from itertools import izip as zip
except ImportError:
    pass

Uses of Zip

Looping over multiple iterables is one of the most common use cases for Python’s zip() function. If you need to iterate through multiple lists, tuples, or any other sequence, then it’s likely that you’ll fall back on zip(). This section will show you how to use zip() to iterate through multiple iterables at the same time.

>>> chars = ['A', 'B', 'C']
>>> ascis = [65, 66, 67]
>>> for c, a in zip(chars, ascis):
    print(f'Char is :{c}')
    print(f'ASCII value is :{a}')

    
Char is :A
ASCII value is :65
Char is :B
ASCII value is :66
Char is :C
ASCII value is :67
>>>

Traversing Dictionaries in Parallel

In Python 3.6 and beyond, dictionaries are ordered collections, meaning they keep their elements in the same order in which they were introduced. If you take advantage of this feature, then you can use the Python zip() function to iterate through multiple dictionaries in a safe and coherent way:

>>> superhero_name = {'name':'Superman', 'universe':'DC', 'league':'Justice League'}
>>> human_name = {'name':'Clark', 'universe':'Metropolis', 'league':'Daily Planet'}
>>> for (k1, v1), (k2, v2) in zip(superhero_name.items(), human_name.items()):
    print(f'{k1} :{v1}')
    print(f'{k2} :{v2}')

    
name :Superman
name :Clark
universe :DC
universe :Metropolis
league :Justice League
league :Daily Planet
>>> 

Unzipping

If you have a list of tuples and want to separate the elements of each tuple into independent sequences. To do this, you can use zip() along with the unpacking operator *, like so:

>>> zipped = [('A', 65), ('B', 66), ('C', 67)]
>>> chars, ascis = zip(*zipped)
>>> chars
('A', 'B', 'C')
>>> ascis
(65, 66, 67)
>>> 

Sorting in Parallel

Using sort()
>>> ascis = [97, 65, 66, 67, 98]
>>> chars = ['a', 'A', 'B', 'C', 'b']
>>> zipped1 = list(zip(ascis, chars))
>>> zipped1.sort() # Sort by number
>>> zipped1
[(65, 'A'), (66, 'B'), (67, 'C'), (97, 'a'), (98, 'b')]
>>> zipped2 = list(zip(chars, ascis))
>>> zipped2.sort() # sort by chars
>>> zipped2
[('A', 65), ('B', 66), ('C', 67), ('a', 97), ('b', 98)]
Using sorted()
>>> sorted(zip(ascis, chars)) # sort by number
[(65, 'A'), (66, 'B'), (67, 'C'), (97, 'a'), (98, 'b')]
>>> sorted(zip(chars, ascis)) # sort by chars
[('A', 65), ('B', 66), ('C', 67), ('a', 97), ('b', 98)]
>>> 

sorted() method approach can be a little bit faster since you’ll need only two function calls: zip() and sorted().
With sorted(), you’re also writing a more general piece of code. This will allow you to sort any kind of sequence, not just lists.

Building Dictionaries

>>> fields = ['first_name', 'last_name', 'salary', 'location']
>>> values = ['Clark', 'Kent', 30000, 'Metropolis']
>>> sup_dict = dict(zip(fileds, values))
>>> sup_dict = dict(zip(fields, values))
>>> sup_dict
{'first_name': 'Clark', 'last_name': 'Kent', 'salary': 30000, 'location': 'Metropolis'}

Update dictionary

>>> field = ['location']
>>> value = ['Gotham']
>>> sup_dict.update(zip(field, value))
>>> sup_dict
{'first_name': 'Clark', 'last_name': 'Kent', 'salary': 30000, 'location': 'Gotham'}
>>> 

Writer profile pic

Prakash on Sep 20, 2020 at 07:09 am


This article is contributed by Prakash. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.