A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/use-enumerate-and-zip-together-in-python/ below:

Use enumerate() and zip() together in Python

Use enumerate() and zip() together in Python

Last Updated : 25 Apr, 2025

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:

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4