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']
Some other articles
Y111 - More on Collections and Sequences Mutable v Immuatble objects in Python, and the implication Accessing variables across subroutine boundaries - Perl, Python, Java and Tcl zip in Python Python for loops - applying a temporary second name to the same object List slices in Python - 2 and 3 values forms, with an uplifting example Python dictionaries - mutable and immutable keys and values This article Sorting - naturally, or into a different order Sorting people by their names Python - access to variables in the outer scope List Comprehensions in Python Anonymous functions (lambdas) and map in Python Callbacks - a more complex code sandwich Last elements in a Perl or Python list Python - extend v append on a list Copying a reference, or cloning What is a callback? Python is a fabulous language Y104 - Lists and Tuples Embedding more complex code into a named block Shuffling a list - Ruby and Python Collections in Python - list tuple dict and string. Spike solutions and refactoring - a Python example Stepping through a list (or an array) in reverse order List slices in Python - 2 and 3 values forms, with an uplifting example All possible combinations from a list (Python) or array (Ruby) Beware - a=a+b and a+=b are different - Python Arrays of arrays - or 2D arrays. How to program tables. This article Traffic lights in Python Python - fresh examples of all the fundamentals Strings as collections in Python Creating and iterating through Python lists Looking for a value in a list - Python Tektronix 4010 series / Python Tuples for loop - how it works (Perl, PHP, Java, C, etc) Python collections - mutable and imutable Python - extend v append on a list The ternary operator in Python Overloading of operators on standard objects in Python P217 - More than Simple Lists and Hashes! Taking the lead, not the dog, for a walk. How to do multidimensional arrays (or rather lists and hashes) in Perl Take the dog on a lead - do not carry her. Perl references. Not multidimentional arrays - but lists of lists. Much more flexible. Perl! From fish, loaves and apples to money, plastic cards and BACS (Perl references explained) Arrays of arrays - or 2D arrays. How to program tables. Adventure with references to lists and lists of references Finding elements common to many lists / arrays Setting up a matrix of data (2D array) for processing in your program This article Further more advanced Perl examples Just pass a pointer - do not duplicate the data Perl references - $$var and $var notations Autovivification - the magic appearance of variables in Perl Course follow-ups Hash of lists in Perl P208 - Lists in Perl Mapping an array / list without a loop - how to do it in Perl 6 Lots of ways of doing the same thing in Perl - list iteration Taking the lead, not the dog, for a walk. Writing more maintainable Perl - naming fields from your data records Stepping through a list (or an array) in reverse order Dark mornings, dog update, and Python and Lua courses before Christmas $ is atomic and % and @ are molecular - Perl This article Fresh Perl Teaching Examples - part 2 of 3 Iterating over a Perl list and changing all items Finding text and what surrounds it - contextual grep The dog is not in trouble Revision / Summary of lists - Perl Perl - lists do so much more than arrays Perl Socket Programming Examples Out of memory during array extend - Perl Perl - map to process every member of a list (array) Perl ... adding to a list - end, middle, start Filtering and altering Perl lists with grep and map Last elements in a Perl or Python list Perl - a list or a hash? C++ and Perl - why did they do it THAT way? Breaking bread Huge data files - what happened earlier? Queues and barrel rolls in Perl The fencepost problem Splitting the difference Context in Perl Conventional restraints removed Course sizes - beware of marketing statistics Comparison Chart for Perl programmers - list functions Perl for breakfast