Wednesday, 23 May 2018

Python enumerate()


Enumerate is a built-in function in Python. It is used when we want to access anumber or a variable in a list along with its counter.
For e,g
>>> A= [2,5,6,7,8,9]
>>> for i in enumerate(A):
print i

will give the output:
(0, 2)
(1, 5)
(2, 6)
(3, 7)
(4, 8)
(5, 9)

See in the output we get tuples in the form ( index,value)

Using list comprehension we can also write:
>>> A= [2,5,6,7,8,9]
>>> B = [i  for i in enumerate(A)]
>>> print B

will give the output:
[(0, 2), (1, 5), (2, 6), (3, 7), (4, 8), (5, 9)] 



We can get output as list of list using the below format:
>>> A= [2,5,6,7,8,9]  
>>> B = [ [i,v]  for i,v in enumerate(A)]  
>>> print B  

will give output:
[[0, 2], [1, 5], [2, 6], [3, 7], [4, 8], [5, 9]]


Enumerate also takes argument that allows to start the counter from that argument.
example:
>>> A= [2,5,6,7,8,9] 
>>> B = [ [i,v] for i,v in enumerate(A,1)] 
>>> print B 

will now give output  : 

[[1, 2], [2, 5], [3, 6], [4, 7], [5, 8], [6, 9]]


















https://docs.python.org/2.3/whatsnew/section-enumerate.html

No comments:

Post a Comment

Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...