Member-only story

Don’t Use for i To Loop Through Multiple Lists. Here is A Better Choice

Richard
Aug 6, 2022

--

Suppose you have two lists:

l1 = [1, 2, 3]l2 = ['a', 'b', 'c']

And you want to loop through them together.

Normal way:

The disadvantage of this approach: if one list is longer than another, we will get an error.

The safer way: use zip function.

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

Even if l1 is longer than l2 , the loop stops at the shorter sequence.

--

--

Richard
Richard

No responses yet

Write a response