![]() |
VOOZH | about |
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:
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.
for var1,var2,.,var n in enumerate(zip(list1,list2,..,list n))
Parameters:
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.
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
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: