iFunction
iFunction

Reputation: 1268

Reuse variable name to point at different data

So I am getting tripped up by what appears to be a variable in Python behaving like a pointer in C i.e. For example:

foo = ['item1', 'item2', 'item3']

now if I assign that list to the value of a dictionary whose key is 'bar':

my_dict['bar'] = foo

all is fine, but now if I do:

foo.clear()

then my_dict['bar'] is now empty implying that foo and my_dict['bar'] are just two different names pointing at the same data. How can I get around this so I can dump foo into my_dict['bar'] and then reuse foo for the next item in the dictionary please?

How can I get around this so that I can reuse 'foo'?

Upvotes: 1

Views: 467

Answers (1)

Luke K
Luke K

Reputation: 895

You're correct in that it's like a pointer. Collections of data, such as lists, dictionaries, objects etc are passed by reference. Therefore when you set mydict["bar"] = foo you were setting it equal to the reference of foo.

To get around this you would need to make a copy of foo. You should get by with a shallow copy

mydict["bar"] = foo[:]

I this case the slice operator will create a new list of all elements in foo, with a new reference value. You could also consider the copy python module, which would have a similar effect but supports deep copy operations. i.e. it create copies of the object itself, and all objects contained within it.

Please also read jasonharper's comment on this. If you don't need a copy of the elements it's more efficient to just create a new empty list

Upvotes: 4

Related Questions