Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Variable/List assignment and changing values

Can anyone explain to me why in the code below that changing the list changes the list in the other but doing the same to single value variables doesn't.

hello = 5
hi = hello
print("hello {}" .format(hello))
print("hi {}".format(hello))
hello = 4
print("hello {}" .format(hello))
print("hi {}".format(hi))

a_list = [1,2,3,4,5]
my_list = a_list

print("a_list {}".format(a_list))
print("my_list {}".format(my_list))


print("my_list {}".format(my_list))

Is this the case with any other value types?

1 Answer

Michael Kelly
Michael Kelly
4,965 Points

Hi Nathan,

When you do this sort of thing with two single value variables, such as x = 2 y = x y = 3 You have two variables that store a place in memory. x stores 2 and is assigned a place in memory that also stores 2. When you set y = 3, the value stored in y is copied in its own place in memory.

With two lists, x = [1,2,3] y = x the values of x are not copied. Setting y = x just tells y to point to the same place in memory that x points. So when you change y[0] you change a value that is stored in memory. That value is the same one that x[0] looks at. Since they are looking at the same place, changing one seems to change the other.

You need to copy the contents of a_list to a new list called my_list to avoid this.