Accessing Index Values in Python's 'for' Loop
When traversing a sequence with a for loop, obtaining the current index may prove useful. However, accessing this index can be tricky.
Inefficient Manual Indexing
One common approach is to manually track the index using a separate counter or index variable:
xs = [8, 23, 45] for i in range(len(xs)): print("item #{} = {}".format(i, xs[i]))
However, this approach is verbose and prone to errors.
Elegant Solution with 'enumerate()'
Python provides a built-in function, enumerate(), that elegantly solves this issue. It returns a sequence of tuples, where each tuple contains the current index and the corresponding element:
for idx, x in enumerate(xs): print("item #{} = {}".format(idx, x))
By utilizing this function, you can access both the index and the element directly, ensuring efficient and error-free indexing.
The above is the detailed content of How Can I Efficiently Access Index Values While Iterating in Python's `for` Loop?. For more information, please follow other related articles on the PHP Chinese website!