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.
1 Answer
+ 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.