+ 2

Python3 list

x = "abcda" for i in x: if x.index(i)==0:print(i) Why am i getting aa

3rd Jul 2019, 9:57 AM
I Am Anushka
4 odpowiedzi
+ 6
index() returns the first occurrence of an element in the list, so the five loops are: if x.index("a") == 0: print("a") # 0 => PRINT a if x.index("b") == 0: print("b") # 1 if x.index("c") == 0: print("c") # 2 if x.index("d") == 0: print("d") # 3 if x.index("a") == 0: print("a") # 0 => PRINT a
3rd Jul 2019, 11:28 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 4
The for loop cycles through each letter in the string. x.index(i) # this gives you the first position of the string where the character i is found. So the value of this expression in each cycle is: 0 1 2 3 0 Because the index of 'a' is 0 and it occured twice in the string, it is printed twice.
3rd Jul 2019, 11:28 AM
Tibor Santa
Tibor Santa - avatar
0
Thank you
3rd Jul 2019, 11:31 AM
I Am Anushka
0
it only reads the index of the first a, 0, so if its 0 it prints a.
2nd Jul 2020, 4:37 AM
Pr0C0d3r
Pr0C0d3r - avatar