Python Forum

Full Version: Noob question about lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi. Noob question (sorry)...

I'm learning Python myself (reading "Head First Python").
Having trouble wrapping my head around why in the below code the integer '5' is removed from 'list_a', even through the pop() method was applied only to 'list_b'.

list_a = [1, 2, 3, 4, 5]
list_b = list_a
list_b.pop()
print("list_a is", list_a)
print("list_b is",list_b)
I understand that the line stating "list_b = list_a" makes the two variables have the same value.
But after that, I expected that 'list_a' and 'list_b' are each their own individual object and that changes made to one wouldn't affect the other.
In other words, I expected the value of 'list_a' to remain [1, 2, 3, 4, 5]

Can someone please help explain this to me?
Thanks Confused
because list_b = list_a you did not make a new list you just renamed it
you want something like this

list_a = [1, 2, 3, 4, 5]
list_b = [i for i in list_a]

list_b.pop()
print("list_a is", list_a)
print("list_b is", list_b)
Both variables point to the same list. You would not think that, but true. This video about variables, by Ned Batchelder, is well worth your time.

Ned B at Pycon 2015
(Nov-19-2020, 01:40 AM)Nickd12 Wrote: [ -> ]you did not make a new list you just renamed it

Thanks Nickd12!

(Nov-19-2020, 02:23 AM)jefsummers Wrote: [ -> ]Both variables point to the same list. You would not think that, but true. This video about variables, by Ned Batchelder, is well worth your time.

Perfect! This video is exactly the explanation that I needed Big Grin