0
Please how does this code snippet work?
a = [0,1,2,3,] for a[-1] in a: print(a[-1]) It outputs 0,1,2,2 but I don't understand why. I thought it should output an Error but I was wrong.
3 odpowiedzi
+ 3
a[-1] means last element in the list.
for i in a is storing each element of a in temporary variable i when looping.
for a[-1] is storing each element of a in the last slot of a. So the last element has the value of second last element when the loop reaches the last slot.
https://code.sololearn.com/cjTMp4kCULX8/?ref=app
This quiz is for brain teasing only. This is something you will avoid doing in actual programming.
+ 2
This seems like magic to me too at first glance. After playing around, I think the real magic is the line:
for a[-1] in a:
This line loop through the value in a array, assign each value to a[-1] in each loop, and print out the a[-1]
Breakdown :
a[-1] = a[0] = 0
a[-1] = a[1] = 1
a[-1] = a[2] = 2
a[-1] = a[-1] = 2
+ 1
I understand better now. Thank you both for your answers!