enumerate[] in Python: Get the element and index from a list
In Python, you can get the element and index [count] from iterable objects such as lists and tuples in a for loop by the built-in function enumerate[].
- Built-in Functions - enumerate[] Python 3.8.5 documentation
This article describes the basics of enumerate[].
- How to use enumerate[]
- Normal for loop
- for loop with enumerate[]
- Start index from 1 with enumerate[]
- Set step with enumerate[]
See the following articles for more information about for loop and how to use enumerate[] and zip[] together.
- for loop in Python [with range, enumerate, zip, etc.]
- Use enumerate[] and zip[] together in Python
How to use enumerate[]
Normal for loop
for loop with enumerate[]
By passing an iterable object in the argument of enumerate[], you can get index, element.
Start index from 1 with enumerate[]
As in the example above, by default the index of the enumerate[] starts from 0.
If you want to start from another number, pass it in the second argument of the enumerate[].
Example starting from 1:
Example starting from the other number:
For example, this is useful when generating a serial number string. It is smarter to pass the starting number in the second argument of the enumerate[] than to calculate i + 1.
Set step with enumerate[]
There is no argument like step to specify increment to enumerate[], but it can be done as follows.
Related Categories
- Python
- List
Related Articles
- Check if the list contains duplicate elements in Python
- Convert pandas.DataFrame, Series and list to each other
- Queue, stack, and deque [double-ended queue] in Python
- Convert lists and tuples to each other in Python
- Extract and replace elements that meet the conditions of a list of strings in Python
- Sort a list of dictionaries by the value of the specific key in Python
- Pretty-print with pprint in Python
- Sort a list, string, tuple in Python [sort, sorted]
- How to flatten a list of lists in Python
- Add an item to a list in Python [append, extend, insert]
- Count elements from a list with collections.Counter in Python
- Cartesian product of lists in Python [itertools.product]
- Remove / extract duplicate elements from list in Python
- Unpack a tuple / list in Python
- Convert a list of strings and a list of numbers to each other in Python