zip sequence to tuple
zip sequence to tuple
A useful tool for parallel iteration is the built-in function zip, which "zips" together the sequences, returning a list of tuples:
zip(sequence1, ...)
returns a list of tuples, where each tuple
contains an item from each of the supplied sequences. The returned
list has the same length as the shortest of the supplied sequences.
names = ['Mike', 'Bob', 'Robert', 'Mary']
ages = [1, 5, 3, 2] # w w w .j a va 2 s .co m
print zip(names, ages)
for name, age in zip(names, ages):
print name, 'is', age, 'years old'
The code above generates the following result.
Zip three tuples
T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)
print T3
print zip(T1,T2,T3)
The code above generates the following result.
Loop over two or more sequences at the same time,
the entries can be paired with the zip()
function.
questions = ['A', 'B', 'C']
answers = ['a', 'b', 'c']
# ww w . j av a 2 s . c om
for q, a in zip(questions, answers):
print 'What is your %s? It is %s.' % (q, a)
The code above generates the following result.