Alex Rivera | Logout

Variable assignment and modification (in python)

Asked 2011-07-22T17:36:46.600
39

When I ran this script (Python v2.6):

a = [1,2]
b = a
a.append(3)
print a
>>>> [1,2,3]
print b
>>>> [1,2,3]

I expected print b to output [1,2]. Why did b get changed when all I did was change a? Is b permanently tied to a? If so, can I make them independent? How?

Edit
Report

1 Answer

4

You might want to look at this link. The problem you have here is a and b both point to the same memory location, so changing one changes the other. Instead, you want to do something like this:

a = [1,2]
b = list(a)
answered 2011-07-22T17:40:48.413

Your Answer