Nikky
Nikky

Reputation: 49

Surprising output of simple Python list program

I am getting bit confused after seeing the output of following Python program:

t = [0,1,2]


t[2:].append(t[0])


print(t)

OUTPUT:

[0,1,2] 

Here, I have taken a list [0,1,2]. Why is the output [0,1,2], and not [0,1,0]? Please someone help me to clear my doubt.

Upvotes: 0

Views: 79

Answers (2)

yashcode17
yashcode17

Reputation: 12

This line of code, do nothing:

t[2:].append(t[0])

For desired result use:

t = [0,1,2]
t2 = t[:2] # we only need 1st and 2nd value from t
t2.append(t[0]) # append 1st value of t in the last of t2 to generate the desired list
print(t2) # print t2 (the desired list)

or

t = [0,1,2]
t[-1] = t[0] # update the last element of list, same as first element
print(t) # print updated list having desired answer

Upvotes: 0

AlanWik
AlanWik

Reputation: 322

It is because t[2:] creates another list, and you are appending to that list, but in the end you are printing the original list t

To give some light:

t is a list object, and when you do t[2:], you are creating a new list object based on the first one. Then, you append to this new object a value and, since you don't store that new object in any variable, the object is lost.

Finally, you are just printing your original, which has not changed, list.

Try this:

new_t = t[2:] # New object with your slice
new_t.append(t[0]) # Appending a value of your old list to this new created list
print(new_t) # Printing the new list

Upvotes: 3

Related Questions