Python3 enumerate() Function
enumerate()is a built-in function in Python used to get both the index and the value while iterating over an iterable object.
Usageenumerate()It allows you to conveniently get both the index (position) and the element itself at the same time, avoiding the use of an extra counter variable.
Word Explanation: enumerateMeans "enumerate", indicating listing one by one.
Basic Syntax and Parameters
Syntax Format
enumerate(iterable, start=0)
Parameter Description
- Parameter iterable:
- Type: Iterable object
- Description: The iterable object to enumerate.
- Parameter start(Optional):
- Type: Integer
- Description: The starting value of the index, defaults to 0.
Function Description
- Return value: Returns an enumerate object (iterator).
- Output: Each iteration returns a tuple (index, value).
Examples
Example 1: Basic Usage
Example
# Basic enumerate usage
fruits = ["apple", "banana", "orange"]
# Get index and value
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Default starts from 0
print("---")
for index, fruit in enumerate(fruits):
print(fruit)
fruits = ["apple", "banana", "orange"]
# Get index and value
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Default starts from 0
print("---")
for index, fruit in enumerate(fruits):
print(fruit)
Expected output:
0: 苹果 1: 香蕉 2: 橙子 --- 0: 苹果 1: 香蕉 2: 橙子
Code explanation:
- enumerate returns (index, value) tuples.
- By default, the index starts at 0.
Example 2: Specify Starting Index
Example
# Start numbering from 1
fruits = ["apple", "banana", "orange"]
for i, fruit in enumerate(fruits, start=1):
print(f"Fruit {i}: {fruit}")
# Start from 10
print("---")
for i, fruit in enumerate(fruits, start=10):
print(f"Index {i}: {fruit}")
fruits = ["apple", "banana", "orange"]
for i, fruit in enumerate(fruits, start=1):
print(f"Fruit {i}: {fruit}")
# Start from 10
print("---")
for i, fruit in enumerate(fruits, start=10):
print(f"Index {i}: {fruit}")
Expected output:
第1个水果: 苹果 第2个水果: 香蕉 第3个水果: 橙子 --- 索引 10: 苹果 索引 11: 香蕉 索引 12: 橙子
The start parameter can specify the starting index.
Example 3: Convert to List
Example
# Convert to list
fruits = ["apple", "banana", "orange"]
result = list(enumerate(fruits))
print(result) # Output: [(0, 'apple'), (1, 'banana'), (2, 'orange')]
# Convert to dictionary (if the values are strings)
result = dict(enumerate(fruits))
print(result) # Output: {0: 'apple', 1: 'banana', 2: 'orange'}
# With list comprehension
squares = [x**2 for x in range(5)]
indexed_squares = [(i, v) for i, v in enumerate(squares)]
print(indexed_squares) # Output: [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
fruits = ["apple", "banana", "orange"]
result = list(enumerate(fruits))
print(result) # Output: [(0, 'apple'), (1, 'banana'), (2, 'orange')]
# Convert to dictionary (if the values are strings)
result = dict(enumerate(fruits))
print(result) # Output: {0: 'apple', 1: 'banana', 2: 'orange'}
# With list comprehension
squares = [x**2 for x in range(5)]
indexed_squares = [(i, v) for i, v in enumerate(squares)]
print(indexed_squares) # Output: [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
Expected output:
enumerate can be easily converted to a list or dictionary.
Example 4: Practical Application
Example
# Find the index of an element
fruits = ["apple", "banana", "orange", "banana", "apple"]
target = "banana"
for index, fruit in enumerate(fruits):
if fruit == target:
print(f"Found {target} at index {index}")
break
# Find all matches with a condition
print("\n"Positions of all bananas:")
for index, fruit in enumerate(fruits):
if fruit == "banana":
print(index, end=" ") # Output: 1 3
# Find character positions in a string
text = "hello"
for i, c in enumerate(text):
print(f"'{c}' is at position {i}")
fruits = ["apple", "banana", "orange", "banana", "apple"]
target = "banana"
for index, fruit in enumerate(fruits):
if fruit == target:
print(f"Found {target} at index {index}")
break
# Find all matches with a condition
print("\n"Positions of all bananas:")
for index, fruit in enumerate(fruits):
if fruit == "banana":
print(index, end=" ") # Output: 1 3
# Find character positions in a string
text = "hello"
for i, c in enumerate(text):
print(f"'{c}' is at position {i}")
Expected output:
enumerate is often used in scenarios that require indices, such as searching, replacing, etc.
Example 5: Working with Dictionaries
Example
# enumerate on a dictionary
person = {"name": "Tom", "age": 20, "city": "Beijing"}
# Iterate over key-value pairs of a dictionary (requires items)
for index, (key, value) in enumerate(person.items()):
print(f"{index}: {key} = {value}")
# Create a dictionary with sequence numbers
items = ["a", "b", "c"]
numbered = {i+1: v for i, v in enumerate(items)}
print(numbered) # Output: {1: 'a', 2: 'b', 3: 'c'}
person = {"name": "Tom", "age": 20, "city": "Beijing"}
# Iterate over key-value pairs of a dictionary (requires items)
for index, (key, value) in enumerate(person.items()):
print(f"{index}: {key} = {value}")
# Create a dictionary with sequence numbers
items = ["a", "b", "c"]
numbered = {i+1: v for i, v in enumerate(items)}
print(numbered) # Output: {1: 'a', 2: 'b', 3: 'c'}
Expected output:
When using enumerate with a dictionary, you need to use the items() method.
Other Extensions
Python3 Built-in Functions