Python | Iterate over multiple lists simultaneously (original) (raw)

Last Updated : 08 May, 2025

In Python, iterating over a single list is straightforward using a for loop. But if we want to iterate over multiple lists at the same time-accessing corresponding elements from each in one loop then we can do so by using these methods:

Using zip()

The built-in zip() function combines elements from multiple iterables. It stops when the shortest iterable is exhausted.

Python `

num = [1, 2, 3] colors = ['red', 'white', 'black'] values = [255, 256]

for n, c, v in zip(num, colors, values): print(n, c, v)

`

Output

1 red 255 2 white 256

**Explanation:

If we want the loop to continue until the longest list is exhausted, use can use **itertools.zip_longest().

Python `

import itertools

num = [1, 2, 3] col = ['red', 'white', 'black'] val = [255, 256]

for n, c, v in itertools.zip_longest(num, col, val): print(n, c, v)

`

Output

1 red 255 2 white 256 3 black None

**Explanation: When a list runs out of items, None is used by default for the missing values.

We can also specify a default value instead of **None in **zip_longest() using the **fillvalue paramaeter.

Python `

import itertools

num = [1, 2, 3] colors = ['red', 'white', 'black'] values = [255, 256]

for n, c, v in itertools.zip_longest(num, colors, values, fillvalue=-1): print(n, c, v)

`

Output

1 red 255 2 white 256 3 black -1

**Note: In Python 2.x, zip() returned a list, and itertools.izip() returned an iterator. In Python 3.x, zip() already returns an iterator, so izip() and izip_longest() are no longer needed.

Using enumerate() with Indexing

If you want to track the index while accessing multiple lists, enumerate() is handy:

Python `

a = [1, 2, 3] b = ['a', 'b', 'c'] c = ['x', 'y', 'z']

for i, val in enumerate(a): print(val, b[i], c[i])

`

Explanation:

Also read: zip(), enumerae(), zip_longest().

Similar Reads

Python List Access





List Iteration Operations





Python List Search Operations






Python List Remove Operations






Python List Concatenation Operations