Python Forum
Unexpected change to a list in a small amount of self-contained code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected change to a list in a small amount of self-contained code
#1
I am using Python 3. I am getting an unexpected result: a list is changing, but I do not understand how/where it changes. Here is my code:
def cool(goodlist, letter):
  goodlist.append("foobar")
  goodlist.append(letter)
  newlist = goodlist
  return newlist

alista = []

var1 = cool(alista, "J")
print(var1)
print(alista)
The above program prints out this:
Output:
['foobar', 'J'] ['foobar', 'J'][/font]
I would expect alista to be empty still. Why and what modifies alista?
Reply


Messages In This Thread
Unexpected change to a list in a small amount of self-contained code - by Johno - Mar-13-2020, 02:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Unexpected behavior accessing list elements. tonyflute 2 2,382 Apr-09-2021, 02:36 PM
Last Post: tonyflute
  Change each character of list into an different characters Angry_bird89 1 2,148 Jun-19-2020, 08:29 AM
Last Post: Angry_bird89
  Print the frequency of each coin for the combinations that sum to the amount N Pranav 3 2,659 May-19-2020, 06:16 AM
Last Post: Pranav
  Program that displays the number with the greatest amount of factors ilusmd 3 2,947 Nov-01-2018, 08:28 PM
Last Post: ichabod801
  i need to change the code woiwoi 3 3,075 Nov-28-2017, 05:37 PM
Last Post: nilamo
  Can't figure out small errors in my code? pythonwizard96 1 4,185 Nov-03-2017, 03:29 PM
Last Post: nilamo
  Looping over amount of attempts Beatenberg 4 6,467 Oct-17-2017, 07:47 AM
Last Post: Beatenberg

Forum Jump:

User Panel Messages

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