+ 1
Why this code returns just one answer (0) whereas the letter p appears twice in the list ?
letters = ['p', 'q', 'r', 's', 'p', 'u'] print(letters.index('p')) 0
8 Respuestas
+ 5
The index() method only returns the first (lowest) index value of an element. To get them all, you would have to use something like [edit:]
print([a for a, b in enumerate(letters) if b == 'p'])
https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/methods/list/index
+ 5
s l You're welcome. I edited my answer because I got it wrong the first time 🙃
+ 3
The code will look only for first occurrence of p.Once it find p it outputs the results.
+ 3
index() method return the index value of an element whenever it occur first in list. if you find the index value of an element when it occur 2nd time in list.you can do like this.
x=['p','a','h','p']
y=x.index('p')
print(x.index('p',y+ 1)) #output=3
+ 2
BMT I wouldn't say the two 'p' elements share the same index position. The second 'p' is at 4.
print(letters[4]) # outputs 'p', no?
https://code.sololearn.com/cOL9iSNYj3S9/?ref=app
+ 1
Thank you very much for your answer, David.
0
Thank you very much for your answer too, Kapil.
0
Thank you very much for this answer, Maninder.