List index | Sololearn: Learn to code for FREE!

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.

11/16/2016 12:29:37 AM

Farhan Ramli

4 Answers

New Answer

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

+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)

+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

0

thanks kirk, now I can use each item in list and have it's index. totally what I need.