Using enumerate()
to Modify Variables In-Place
enumerate()
is a built-in Python function that returns both the index and the value of items in a sequence (like lists, tuples, or strings) during iteration. Its primary purpose is to keep a count of iterations. But when combined with sequences that support in-place modification (like lists), it can be a powerful tool to update values directly.
for index, value in enumerate(sequence):
...
Say you have a list of numbers, and you want to square all even numbers. Using enumerate()
, you can do this in-place:
numbers = [1, 2, 3, 4, 5]
for idx, num in enumerate(numbers):
if num % 2 == 0:
numbers[idx] = num ** 2
After this loop, the numbers
list will be updated to [1, 4, 3, 16, 5]
.
enumerate()
works seamlessly with lists because they are mutable. However, for immutable sequences like strings and tuples, you can’t modify the original variable in-place.dict.items()
.By default, enumeration starts at 0. However, you can provide a second argument to start from a different index:
for index, value in enumerate(sequence, start=1):
...
In the above code, enumeration starts at 1.