0

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.

2
  • 8
    t[2:] is a slice, which means it is a copy of part of the list. t still holds your original list. Altering the copy doesn't affect the original. Commented Jan 4, 2021 at 16:56
  • @khelwood, your comment should be an answer :) Commented Jan 4, 2021 at 17:01

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.