Main Content

Copying - duplicating data, or just adding a name? Perl and Python compared

Archive - Originally posted on "The Horse's Mouth" - 2010-10-12 06:53:52 - Graham Ellis

When you copy a list in Perl, you're duplicating the data and you end up with two distinct copies ... but when you copy a list in Python, you're copying the reference so that you end up with two names for the same variable - almost like an alias.

So in Perl - with two different copies - you end up with two sets of data that can diverge as you modify them, but in Python, if you modify the variable under one name, you're also modifying it under the other name.

If you want the Perl behaviour in Python, you can use a list slice to do the copy - replacing
  tea = lunch
with
  chucked = lunch[:]
but even that does only a "shallow" copy - it duplicates the references to objects within the list, so that if those objects are mutable and you change their contents, you're still chaning both.

So in my example above:
  lunch[0] = "Mints"
also changes tea, but does not alter chucked whereas
  lunch[2][1] = "Beans"
also changes tea and chucked

There are source code examples here - [source in Perl] and [source in Python]

Original Data:
["Sausages","Mash",["Sweetcorn","Peas"],"Brocolli"]

In @tea, in Perl ... unchanged:
["Sausages","Mash",["Sweetcorn","Peas"],"Brocolli"]

In tea, in Python ... Mints and Beans have replaced Sausages and Peas:
['Mints', 'Mash', ['Sweetcorn', 'Beans'], 'Brocolli']

and in chucked, in Python ... Beans have replaced peas:
['Sausages', 'Mash', ['Sweetcorn', 'Beans'], 'Brocolli']