Open In App

Use enumerate() and zip() together in Python

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, zip() combines multiple iterables into tuples, pairing elements at the same index, while enumerate() adds a counter to an iterable, allowing us to track the index. By combining both, we can iterate over multiple sequences simultaneously while keeping track of the index, which is useful when we need both the elements and their positions. For Example:

Python
a = [10, 20, 30]
b = ['a', 'b', 'c']

for idx, (num, char) in enumerate(zip(a,b), start=1):
    print(idx, num, char)

Output
1 10 a
2 20 b
3 30 c

Explanation: Loop prints the index (starting from 1) along with the corresponding elements from lists a and b. zip() pairs the elements and enumerate() tracks the index starting from 1.

Syntax of enumerate() and zip() together

for var1,var2,.,var n in enumerate(zip(list1,list2,..,list n))

Parameters:

  • zip(list1, list2, …, list_n) combines multiple iterables element-wise into tuples.
  • enumerate(iterable, start=0) adds an index (starting from start, default is 0) to the tuples.
  • var1, var2, …, var_n variables to unpack the indexed tuple.

Examples

Example 1: Iterating over multiple lists

Python
a = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh']
b = ['java', 'python', 'R', 'cpp', 'bigdata']
c = [78, 100, 97, 89, 80]

for i, (name, subject, mark) in enumerate(zip(a, b, c)):
    print(i, name, subject, mark)

Output
0 sravan java 78
1 bobby python 100
2 ojaswi R 97
3 rohith cpp 89
4 gnanesh bigdata 80

Explanation: zip() pairs elements from a, b and c into tuples, while enumerate() adds an index. The loop extracts and prints i, name, subject and mark.

Example 2: Storing the tuple output

Python
a = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh']
b = ['java', 'python', 'R', 'cpp', 'bigdata']
c = [78, 100, 97, 89, 80]

for i, t in enumerate(zip(a,b,c)):
    print(i, t)

Output
0 ('sravan', 'java', 78)
1 ('bobby', 'python', 100)
2 ('ojaswi', 'R', 97)
3 ('rohith', 'cpp', 89)
4 ('gnanesh', 'bigdata', 80)

Explanation: zip() pairs elements from a, b and c into tuples, while enumerate() adds an index. The loop extracts and prints i and the tuple t containing name, subject and mark.

Example 3: Accessing Tuple Elements Using Indexing

Python
a = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh']
b = ['java', 'python', 'R', 'cpp', 'bigdata']
c = [78, 100, 97, 89, 80]

for i, t in enumerate(zip(a,b,c)):
    print(i, t[0], t[1], t[2])

Output
0 sravan java 78
1 bobby python 100
2 ojaswi R 97
3 rohith cpp 89
4 gnanesh bigdata 80

Explanation: zip() pairs elements from a, b and c into tuples, while enumerate() adds an index. The loop extracts and prints i, t[0] (name), t[1] (subject) and t[2] (mark) from each tuple.

Related Articles:



Next Article
Article Tags :
Practice Tags :

Similar Reads