+ 2
Python3 list
x = "abcda" for i in x: if x.index(i)==0:print(i) Why am i getting aa
4 Respostas
+ 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
+ 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.
0
Thank you
0
it only reads the index of the first a, 0, so if its 0 it prints a.