Use the built-in function enumerate()
:
for idx, x in enumerate(xs):
print(idx, x)
It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i]
or manually manage an additional state variable.
Check out PEP 279 for more.
More Related Contents:
- Strange result when removing item from a list while iterating over it
- What is the most “pythonic” way to iterate over a list in chunks?
- Modifying list while iterating [duplicate]
- Iterate through pairs of items in a Python list [duplicate]
- Removing Item From List – during iteration – what’s wrong with this idiom?
- How to avoid “RuntimeError: dictionary changed size during iteration” error?
- Can’t modify list elements in a loop [duplicate]
- Python – TypeError: ‘int’ object is not iterable
- How to iterate over a list in chunks
- How do I loop through a list by twos? [duplicate]
- Assigning values to variables in a list using a loop
- python assign values to list elements in loop
- How to transform string of space-separated key,value pairs of unique words into a dict
- Why do I get “List index out of range” when trying to add consecutive numbers in a list using “for i in list”? [duplicate]
- Why does a for-loop with pop-method (or del statement) not iterate over all list elements [duplicate]
- Why doesn’t assigning to the loop variable modify the original list? How can I assign back to the list in a loop? [duplicate]
- Iterate through adjacent pairs of items in a Python list [duplicate]
- How can I avoid “RuntimeError: dictionary changed size during iteration” error?
- Loop over 2 lists, repeating the shortest until end of longest [duplicate]
- Loop through list with both content and index [duplicate]
- Count duplicates between 2 lists
- How to find the maximum number in a list using a loop?
- Strange result when removing item from a list while iterating over it in Python
- Deleting certain elements in a list [closed]
- How to check if all elements of a list match a condition?
- Pandas DataFrame to List of Dictionaries
- Why does list ask about __len__?
- How to create a fix size list in python?
- Python: How to sort a list of dictionaries by several values?
- How does str(list) work?