What is
Returns a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
So the syntax is:
The real world example:
If number of elements differ:
As you can see from above, list is truncated to the length of the shortest argument sequence
You can also use
The output:
#python #zip #unzip #iterators
zip
function in Python
?zip
function gets iterables
as input and returns a tuple as output, it actually aggregates data:zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Returns a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
So the syntax is:
zip(*iterables)
The real world example:
numberList = [1, 2, 3]
strList = ['one', 'two', 'three']
# Two iterables are passed
result = zip(numberList, strList)
{(2, 'two'), (3, 'three'), (1, 'one')}
If number of elements differ:
numbersList = [1, 2, 3]
numbersTuple = ('ONE', 'TWO', 'THREE', 'FOUR')
result = zip(numbersList, numbersTuple)
print(set(result))
{(2, 'TWO'), (3, 'THREE'), (1, 'ONE')}
As you can see from above, list is truncated to the length of the shortest argument sequence
numbersList
.You can also use
zip
to actually unzip
data:coordinate = ['x', 'y', 'z']
value = [3, 4, 5, 0, 9]
result = zip(coordinate, value)
resultList = list(result)
print(resultList)
c, v = zip(*resultList)
print('c =', c)
print('v =', v)
The output:
[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)
#python #zip #unzip #iterators