0

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..

ProGM
  • 6,949
  • 4
  • 33
  • 52
Dalia
  • 11
  • 1
  • possible duplicate of [Finding the index of an item given a list containing it in Python](http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python) – albciff Oct 14 '14 at 10:55

3 Answers3

2

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.

0xhughes
  • 2,703
  • 4
  • 26
  • 38
  • 1
    And you can do "[i for i,j in enumerate(my_list) if j == valueToFind]" to get an array of indexes when there are multiple values – user3885927 Oct 09 '14 at 04:14
0
>>> [1, 2, 3, 4].index(4)
3
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

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]
Yanuar Kusnadi
  • 233
  • 2
  • 7