April 24, 2008

Python array copy

Filed under: cool, dev, one-liner, python, tip, tool — michaelangela @ 9:52 pm

I had heard about passing by reference vs. passing by value. Here is a case of passing by reference.

In [76]: a=[1,2]
In [77]: b=a
In [78]: b.append(3)
In [79]: a
Out[79]: [1, 2, 3]

That’s not what I was looking for. I was hoping to get 'b' to be [1, 2, 3] leaving 'a' unchanged. Oops. It passed 'a' to 'b' by reference so any changes to 'b' affected 'a'. So… need a copy. Simplest way I’ve seen of copying an array in python so far is to use [:].

Learn Python in 10 minutes | Poromenos’ Stuff

A useful use of the array range colon is to copy an array:

newary = oldary[:]



  1. Succinct and helpful. Thank you.

    Comment by ertyseidel — June 25, 2010 @ 3:18 pm

  2. #add empty mutation also copies
    a = [1,2]
    b = a + []
    print a

    Comment by Aduen (@Aduen) — March 26, 2012 @ 3:20 pm

  3. properti

    Python array copy | Ramblings

    Trackback by properti — September 21, 2015 @ 4:10 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: