Search notes:
Python: zip
The built-in function
zip
has nothing to do with
zip files . Rather, it creates an
iterator from a set of other iterators. The created iterator emits
tuples when it is iterated over. The elements of the n-nth tuple correspond to the n-th element in the input-iterators.
numbers = [ 1 , 2 , 3 , 4 , 5 ]
letters = ['a' , 'b' , 'c' , 'd' , 'e' ]
words = ['one', 'two', 'three', 'four', 'five']
zipped = zip(numbers, letters, words)
for triple in zipped:
print(triple)
#
# (1, 'a', 'one')
# (2, 'b', 'two')
# (3, 'c', 'three')
# (4, 'd', 'four')
# (5, 'e', 'five')
Unequal length of «input» iterators
If the «input»-iterators provide an unequal number of elements, the zip()
function just stops after finishing the shortest iterator:
numbers = [ 1 , 2 , 3 ]
letters = ['a' , 'b' , 'c' , 'd' , 'e' ]
words = ['one', 'two', 'three', 'four' ]
zipped = zip(numbers, letters, words)
for triple in zipped:
print(triple)
#
# (1, 'a', 'one')
# (2, 'b', 'two')
# (3, 'c', 'three')
Unzipping
pairs = [ (1, 'one' ),
(2, 'two' ),
(3, 'three')
]
nums, words = zip(*pairs)
print(nums )
# (1, 2, 3)
print(words)
# ('one', 'two', 'three')
Transposing a matrix
numbers = [ ( 'one' , 'two' , 'three'),
( 'eins', 'zwei', 'drei' ),
( 'un' , 'dos' , 'tres' )
]
transposed = list(zip(*numbers))
print(transposed)
#
# [('one', 'eins', 'un'), ('two', 'zwei', 'dos'), ('three', 'drei', 'tres')]