Python enumerate() Function: Explained with Examples
The 'enumerate()' function in Python is a handy tool for iterating over a sequence (such as a list, tuple, or string) and obtaining both the index and the value of each element during the iteration.
Syntax:
enumerate(iterable, start=0)
Here's a breakdown of the syntax:
- 'iterable': This is the sequence (list, tuple, string, etc.) you want to iterate over.
- 'start': This is an optional argument that specifies the starting value for the count. If you omit it, the count will start from 0 by default.
Example Usage:
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)
Output:
0 apple
1 banana
2 cherry
Explanation:
- Initialization: The 'fruits' list contains the names of some fruits.
- Iteration: The 'enumerate(fruits)' function iterates over the 'fruits' list. In each iteration, it returns a tuple containing the index (starting from 0) and the corresponding fruit name.
- Unpacking: The 'for' loop unpacks the tuples returned by 'enumerate()' into the variables 'i' (index) and 'fruit'.
- Printing: The values of 'i' and 'fruit' are printed for each iteration, demonstrating the index-value pairs generated by 'enumerate()'.
Advantages of Using 'enumerate()':
- Conciseness: It simplifies iterating over a sequence and accessing both the index and value in a single line of code.
- Readability: The code becomes more readable by clearly associating each value with its index.
- Flexibility: The 'start' parameter allows you to customize the starting count if needed.
Practical Applications:
- Creating numbered lists: Displaying items in a list with sequential numbers.
- Tracking progress: Keeping track of the current iteration in a loop.
- Mapping values to keys: Creating dictionaries or other data structures by associating values with specific indices.
原文地址: https://www.cveoy.top/t/topic/mw2j 著作权归作者所有。请勿转载和采集!