why python index is not showing the repeated letter index | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

why python index is not showing the repeated letter index

for ex: list = ['p','q','r','s',p'] if yunrun the code you see only index0 not the 3

6th Jun 2020, 9:51 AM
Pavithra B G
7 Answers
+ 16
missing a single quote at the last index.
6th Jun 2020, 9:57 AM
Satnam
Satnam - avatar
+ 10
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]
6th Jun 2020, 1:53 PM
Lothar
Lothar - avatar
+ 9
Kuba, after a restart of python it was ok. Sorry!
6th Jun 2020, 2:08 PM
Lothar
Lothar - avatar
+ 7
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
6th Jun 2020, 11:01 AM
HonFu
HonFu - avatar
+ 6
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
6th Jun 2020, 10:00 AM
Namit Jain
Namit Jain - avatar
+ 6
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[0] for x in enumerate(L) if x[1]==1)) This will create the enumerate object on the fly and will populate the indexes (x[0]) based on the values (x[1]) -- and will of course populate only those which equal to 1 (for example).
6th Jun 2020, 12:10 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 6
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
6th Jun 2020, 2:02 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar