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.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.