⊗pyPmLpSI 158 of 208 menu

Iterating Over Sequences Simultaneously in Python

To iterate over several sequences at once, you can use the zip function. In this case, all elements of the sequences will be output as tuples consisting of elements with the same index.

Example

Let us have two lists:

lst1 = ['a', 'b', 'c'] lst2 = [1, 2, 3]

Let's output their elements in pairs:

for el in zip(lst1, lst2): print(el)

The result of the executed code:

('a', 1) ('b', 2) ('c', 3)

Example

You can also iterate over sequences of different types. Let's loop through the zip function and pass a set and a tuple:

st = {'a', 'b', 'c'} tlp = (1, 2, 3) for el in zip(st, tlp): print(el)

The result of the executed code:

('a', 1) ('b', 2) ('c', 3)

Example

If the length of one sequence is greater than the second, then they will iterate over the elements of the smaller one:

lst1 = ['a', 'b', 'c', 'd', 'e'] lst2 = [1, 2, 3, 4] for el in zip(lst1, lst2): print(el)

The result of the executed code:

('a', 1) ('b', 2) ('c', 3) ('d', 4)

Example

Using the zip function, you can also iterate over three sequences. To do this, we list them all in the function parameter, separated by commas:

lst1 = ['a1', 'b1', 'c1'] lst2 = ['a2', 'b2', 'c2'] lst3 = ['a3', 'b3', 'c3'] for el in zip(lst1, lst2, lst3): print(el)

The result of the executed code:

('a1', 'a2', 'a3') ('b1', 'b2', 'b3') ('c1', 'c2', 'c3')

Practical tasks

Two lists are given:

tst1 = [1, 3, 5] tst2 = [2, 4, 6]

Print their elements in pairs as a tuple.

Two lists are given:

tst1 = ['a', 'b', 'c'] tst2 = ['d', 'e', 'f']

Get the following list from them:

['a', '1', 'b', '2', 'c', '3']

Three lists are given:

tst1 = [11, 12, 13, 14] tst2 = [21, 22, 23, 24] tst3 = [31, 32, 33, 34]

Add the corresponding elements of these lists and write the result in a new list. The summation will proceed according to the following principle:

[ 11 + 21 + 31, 12 + 22 + 32, 13 + 23 + 33, 14 + 24 + 34, ]
byenru