0
Need explanation on this code I came across in a challenge
a = [1, 1, 2, 3, 5, 8] for a[1] in a: pass print(a) #output: [1, 8, 2, 3, 5, 8]
2 odpowiedzi
+ 4
Are you familiar with for loop?
a = [ 1, 1, 2, 3, 5, 8]
If you simply execute
for i in a:
print(i)
It will print all the elements of a because every time it is assigned the next element of list. in the end of the loop, i is assigned the value of last element.
Similarly
for a[1] in a:
pass
As the loop is executed
a [1] is first assigned 1
Then a[1]. = 1
a[1]. = 2
a[1] = 3
a[1] = 5
a[1] = 8
At the end of the loop, the element at index 1 is replaced with the last element that is 8.
Put a print(a) in for loop and you can see this pattern.
If you put another number after 8 in list, the element at index 1 will be replaced the value of that element.
+ 1
Utkarsh Sharma I am familiar with for loop. I understood your explanation perfectly, thank you so much. I will most definetly put print(a) in for loop to see the pattern aswell!