MyInternships.in

Python Advanced

Python enumerate and zip

enumerate() and zip() are two small but powerful built-in functions that make loops cleaner: one gives you the index alongside each value, the other pairs up multiple lists at once.


enumerate() — Index and Value

Normally, looping over a list only gives you the value. If you also need the position of each item, wrap the list in enumerate(), which returns pairs of (index, value) that you can unpack directly in the for loop.

Using enumerate
Python
fruits = ["apple", "banana", "mango"]

for index, fruit in enumerate(fruits):
    print(index, fruit)
Output
Output
0 apple
1 banana
2 mango

You can also start counting from a number other than zero by passing a start argument, which is handy for user-facing numbering like "Item 1", "Item 2".

Starting from 1
Python
for position, fruit in enumerate(fruits, start=1):
    print(f"{position}. {fruit}")

zip() — Pairing Iterables

zip() takes two or more iterables and combines them element by element into tuples, stopping as soon as the shortest iterable runs out. It is perfect for looping over related lists together, like names and scores.

Pairing names and scores
Python
names = ["Aarav", "Priya", "Rohan"]
scores = [88, 92, 76]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")
💡

zip() stops at the shortest input, so if your lists have different lengths, the extra items in the longer list are silently ignored.

Unzipping

You can also reverse the process: unpack a zipped set of pairs back into separate tuples using zip() together with the unpacking operator *.

Unzipping pairs
Python
pairs = [("Aarav", 88), ("Priya", 92), ("Rohan", 76)]
names, scores = zip(*pairs)

print(names)
print(scores)
Output
Output
('Aarav', 'Priya', 'Rohan')
(88, 92, 76)
FunctionPurpose
enumerate(iterable)Adds an index to each item while looping
zip(a, b, ...)Combines multiple iterables into tuples
zip(*pairs)Unzips a list of tuples back into separate groups
ℹ️

Both enumerate() and zip() return iterator objects, so wrap them in list() if you need to see or reuse all the results at once.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships