+ 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

21st Sep 2018, 10:55 AM
s l
8 Antworten
+ 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
21st Sep 2018, 11:06 AM
David Ashton
David Ashton - avatar
+ 5
s l You're welcome. I edited my answer because I got it wrong the first time 🙃
21st Sep 2018, 11:28 AM
David Ashton
David Ashton - avatar
+ 3
The code will look only for first occurrence of p.Once it find p it outputs the results.
21st Sep 2018, 12:50 PM
Kapil Bansal
Kapil Bansal - avatar
+ 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
21st Sep 2018, 4:13 PM
Maninder $ingh
Maninder $ingh - avatar
+ 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
21st Sep 2018, 3:52 PM
David Ashton
David Ashton - avatar
+ 1
Thank you very much for your answer, David.
21st Sep 2018, 11:09 AM
s l
0
Thank you very much for your answer too, Kapil.
21st Sep 2018, 1:20 PM
s l
0
Thank you very much for this answer, Maninder.
21st Sep 2018, 11:27 PM
s l