Noob question about lists - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Noob question about lists (/thread-31031.html) |
Noob question about lists - adifrank - Nov-19-2020 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 RE: Noob question about lists - Nickd12 - Nov-19-2020 because list_b = list_a you did not make a new list you just renamed it RE: Noob question about lists - Nickd12 - Nov-19-2020 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) RE: Noob question about lists - jefsummers - Nov-19-2020 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 RE: Noob question about lists - adifrank - Nov-19-2020 (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 |