Today our python built-in function is enumerate() which is very much useful to generate iterator element along with index.
Need of enumerate() function in Python:
Some times we require to generate a sequence of elements in a list or tuple along with their index. Let us see an example. I have a list L1=[23, 56, ‘surendra’, ‘test’, ‘abc’] and I want to generate an output as
0 23 1 56 2 surendra 3, test 4 abc
To get this output, we have to depend on len() and range() functions as shown below.
>>> for i in range(len(L1)):
... print i, L1[i]
...
0 23
1 56
2 surendra
3 test
4 abc
This can be achieved with enumerate() function as well.
Python enumerate() function syntax:
enumerate(iterator, index-number)
Examples: Let us start with enumerate() function with some examples and see how we can use these examples in Python coding.
Example1: Enumerate a list along with it’s index
>>> for i, item in enumerate(L1):
... print i, item
...
0 23
1 56
2 surendra
3 test
4 abc
Example2: Select index instead of default index
>>> [[i,j] for i,j in enumerate(L1, 3)]
[[3, 23], [4, 56], [5, 'surendra'], [6, 'test'], [7, 'abc']]
Example3: Generate a list of tuples each tuple have index and it’s element.
>>> [(i,j) for i, j in enumerate(L1)]
[(0, 23), (1, 56), (2, 'surendra'), (3, 'test'), (4, 'abc')]
Example4: Generate a list of lists with each list containing list element and it’s index
>>> [[i,j] for i, j in enumerate(L1)]
[[0, 23], [1, 56], [2, 'surendra'], [3, 'test'], [4, 'abc']]
Example5: Generate sets from a list of which each set contain list element and it’s index
>>> [{i,j} for i, j in enumerate(L1)]
[set([0, 23]), set([56, 1]), set([2, 'surendra']), set(['test', 3]), set(['abc', 4])]
Example6: Generate a dictionary from a list of which contain index as dictionary key and element as dictonary value.
>>> {i:j for i, j in enumerate(L1)}
{0: 23, 1: 56, 2: 'surendra', 3: 'test', 4: 'abc'}
or
>>> dict(enumerate(L1))
{0: 23, 1: 56, 2: 'surendra', 3: 'test', 4: 'abc'}
Related functions: list(), tuple(), set(), dict()
Complete python built-in function list.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018