Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Noob question about lists
#1
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
Reply
#2
because list_b = list_a you did not make a new list you just renamed it
Reply
#3
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)
Reply
#4
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
adifrank likes this post
Reply
#5
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Function not scriptable: Noob question kaega2 3 1,134 Aug-21-2022, 04:37 PM
Last Post: kaega2
  beginner question about lists and functions sudonym3 5 2,666 Oct-17-2020, 12:31 AM
Last Post: perfringo
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,312 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Noob question: why is shapesize() not working for my turtle adifrank 8 5,662 Sep-09-2020, 11:13 PM
Last Post: adifrank
  Noob question adifrank 6 2,685 Aug-18-2020, 11:50 PM
Last Post: adifrank
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,187 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Noob Question: Sample Data csn113 1 2,136 Feb-18-2019, 06:35 PM
Last Post: micseydel
  Noob question on Mac python3, pydoc3 JamesNJ 0 2,282 Oct-08-2018, 04:26 AM
Last Post: JamesNJ
  Maya Python Noob Question Iurii_Ledin 2 3,234 Jun-08-2018, 09:09 PM
Last Post: Iurii_Ledin
  Noob question about python and Maxplus Strator 0 2,615 May-16-2017, 05:07 PM
Last Post: Strator

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020