7 AnswersNew Answer
missing a single quote at the last index.
Using enumerate(), mentioned by Kuba, returns a tuple like: (index, value). These can be unpacked to individual variables like: a = "MXKLMN" x = 'M' print([i for i, e in enumerate(a) if e == x]) # output: [0, 4]
Kuba, after a restart of python it was ok. Sorry!
index allows you to set a start point for the search. Like this, you can - for example using a loop - find later occurrences of that item. numbers = (5, 7, 3, 6, 7) print(numbers.index(7)) # 1 print(numbers.index(7, 2)) # 4
This is because the index syntax only returns the index of the first occurence of a particular element in a list or a string... In order to find all the indices you can do: If you know the substring then simply use the re module and then the findall syntax.. if you don't know then: list = ['p','q','r','p'] new =  for i in list: new.append(list.count(i)) [HERE the new list has numbers like this: [2,1,1,1,2]] for i in new: if i != 1: print(new.index(i), end = " ") I hope this helps you
If you want a quick solution to that, you might exploit enumerate() for this: L = [1,2,3,4,2,3,1,1,4,5,3,2] print(list(x for x in enumerate(L) if x==1)) This will create the enumerate object on the fly and will populate the indexes (x) based on the values (x) -- and will of course populate only those which equal to 1 (for example).
Lothar Really? I ran it as a code and it returns a proper output. I even removed the redundant list envelope around the enumerate, it's not needed: https://code.sololearn.com/cY88j3vQE4Vw/?ref=app