0

How come the output isn’t a repetitive set of numbers?

a=[0,1,2,3] for a[-1] in a: print(a[-1]) Why is the output “0 1 2 2”? When i substitute the “-1” with other numbers within range, the output is a set of repetitive number, this one is an exception.

28th Mar 2019, 7:04 AM
Sergio Chan
Sergio Chan - avatar
1 Odpowiedź
+ 5
a[-1] refers to the last element of the list, according to the slicing syntax. Your for loop means that you are using the last element of the list as "iterator variable", so it is changed at every step of the loop to the current element in the loop. loop 1: a = [0,1,2,0] loop 2: a = [0,1,2,1] loop 3: a = [0,1,2,2] loop 4: a = [0,1,2,2] and you are printing the last element in each cycle.
28th Mar 2019, 7:36 AM
Tibor Santa
Tibor Santa - avatar