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.
11/16/2016 12:29:37 AMFarhan Ramli
4 AnswersNew Answer
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-python-for-loops >>> a=list('Jello') >>> for idx, val in enumerate(a): ... print(idx, val) ... 0 J 1 e 2 l 3 l 4 o
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)
@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
thanks kirk, now I can use each item in list and have it's index. totally what I need.