0

List index

based on code below, how to retrieve index of list from n instead of a. is it possible? objective, want to do something with list using for loop, and if possible dont want to use variable a in loop. a = ['a', 'b', 'c', 'd'] for n in a: if n == 'c': x = a.index('c') print(x) other alternative is set i= 0 before for loop and increase val i by 1 each loop. but prefer a solution that run once only, if n='c', then do something to get index.

16th Nov 2016, 12:29 AM
Farhan Ramli
Farhan Ramli - avatar
4 Respostas
+ 4
Use enumerate. With ~4000 upvotes between the question and answer it's been important to people. http://stackoverflow.com/questions/522563/accessing-the-index-in-JUMP_LINK__&&__python__&&__JUMP_LINK-for-loops >>> a=list('Jello') >>> for idx, val in enumerate(a): ... print(idx, val) ... 0 J 1 e 2 l 3 l 4 o
16th Nov 2016, 10:11 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
To make it easier, you could do x = n , or even just print(n) . To make it even shorter, you could cut out that for loop and have it be something like: if 'c' in a: cout a.index(c)
16th Nov 2016, 4:29 AM
Keto Z
Keto Z - avatar
+ 1
@Keto - If I want the second 'l'? >>> a=list('Jello') >>> if 'l' in a: ... print( a.index('l')) ... 2 # first l >>> Also I don't have 'cout' in Python. Are you using it like this, at question "Can I use C++'s syntax for ostreams: cout ..." http://norvig.com/python-iaq.html
16th Nov 2016, 10:18 AM
Kirk Schafer
Kirk Schafer - avatar
0
thanks kirk, now I can use each item in list and have it's index. totally what I need.
16th Nov 2016, 2:27 PM
Farhan Ramli
Farhan Ramli - avatar