Skip to content Skip to sidebar Skip to footer

Why Does It Prints Like This

How does the iteration takes place in the following snippet? a=[0,1,2,3] b=[] for a[-1] in a: b.append(a[-1]) print(b) Output is [0,1,2,2]

Solution 1:

Python for loops use assignment which can lead to interesting results if not used correctly.

Your example can be simplified to reflect this better. Since a[-1] accesses the last element in a, the following code will actually modify a:

a = [0, 1]
for a[-1] in [9]:
    passprint(a)

outputs

[0, 9]

Post a Comment for "Why Does It Prints Like This"