I'm new to python... I'm sorry if my question sounds too amateurish.
my_list = [1, 2, 3, 4]
I need a function that gives me the position (or index when I give it the item)
for example, the index of 4 would be 3..
I'm new to python... I'm sorry if my question sounds too amateurish.
my_list = [1, 2, 3, 4]
I need a function that gives me the position (or index when I give it the item)
for example, the index of 4 would be 3..
http://www.tutorialspoint.com/python/list_index.htm
>>> my_list = [1, 2, 3, 4]
>>> my_list.index(4)
3
The built-in list method index will return the index position of the first value located which is specified in the index method's argument.
if you need more alternative to access your list, you can create tuple of pair of index and value
>>> l = list(enumerate([1, 2, 3, 3, 4, 4]))
>>> l
[(0, 1), (1, 2), (2, 3), (3, 3), (4, 4), (5, 4)]
With list of tuples, you can access or filter based on index or value For example :
Filter : Return all indexes with value = 3
>>> [tup[0] for tup in l if tup[1]==3]
[2, 3]
>>> [tup for tup in l if tup[1]==3]
[(2, 3), (3, 3)]
Filter : Return value of index = 3
>>> [tup[1] for tup in l if tup[0]==4]
[4]