+ 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
7 odpowiedzi
+ 16
missing a single quote at the last index.
+ 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]
+ 9
Kuba, after a restart of python it was ok. Sorry!
+ 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
+ 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
+ 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).
+ 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