Enumerate
What Is Enumerate?
- Enumerate means to mention a collection of things one by one. In Python, the
enumerate()function helps us iterate over an iterable (like a list, tuple, or string) and access both the index and the item in each iteration.
Why Use Enumerate?
- Using a
forloop with an iterable lets you access only the items. To also access the index, you would usually use awhileloop with a counter, which is not as concise. Enumerate solves this problem by providing both the index and item in a single iteration.
How to Use Enumerate:
- The
enumerate()function returns an enumerated object, which is itself an iterable. Syntax:
pythonfor index, item in enumerate(iterable): print(index, item)
Examples and Exercises:
- Enumerate a List:
Iterate over a list of strings and print both the index and the item.
pythonmyList = ['apple', 'banana', 'cherry'] for index, item in enumerate(myList): print(index, item)Output:
0 apple 1 banana 2 cherry
- Enumerate a Tuple:
Iterate over a tuple of items and print both the index and the item.
pythonmyTuple = ('apple', 25, 'India') for index, item in enumerate(myTuple): print(index, item)Output:
0 apple 1 25 2 India
- Enumerate a String:
Iterate over a string and print both the index and the character.
pythonmyString = 'apple' for index, item in enumerate(myString): print(index, item)Output:
0 a 1 p 2 p 3 l 4 e
- Enumerate a Set:
Sets are unordered collections, so the index may change when you rerun the program. Still, you can enumerate a set and print the index and item.
pythonmySet = {'apple', 'banana', 'cherry'} for index, item in enumerate(mySet): print(index, item)Output:
0 cherry 1 banana 2 apple
Exercises:
- Enumerate a List:
- Create a list of your favorite sports and use
enumerate()to print each sport with its index.
- Create a list of your favorite sports and use
- Enumerate a Tuple:
- Create a tuple of your favorite movies and use
enumerate()to print each movie with its index.
- Create a tuple of your favorite movies and use
- Enumerate a String:
- Write a program that takes a string input from the user and uses
enumerate()to print each character with its index.
- Write a program that takes a string input from the user and uses
- Enumerate with a Different Starting Index:
Use the
enumerate()function to start indexing from 1 instead of 0 for a list of numbers.pythonmyNumbers = [10, 20, 30, 40] for index, item in enumerate(myNumbers, start=1): print(index, item)Output:
1 10 2 20 3 30 4 40
Summary:
- The
enumerate()function in Python is a powerful tool that simplifies iterating over an iterable while accessing both the index and item. It is particularly useful for creating concise and readable code. Practice usingenumerate()with different types of iterables to understand its benefits!