How to copy list in python

Python: How to Copy a List? (The Idiomatic Way)

But first, let’s talk about what copying a list actually means.

Let’s take a look at this example

>>> a = [1, 2, 3, 4, 5] >>> b = a >>> a [1, 2, 3, 4, 5] >>> b [1, 2, 3, 4, 5]

In the example above, is b a copy of a?

The answer is actually No

b is in fact a, they both refer to the same python object.

Let’s check what happens to b when we modify a.

As you can see, changing the value of a[0] also changes the value of b[0] because they both refer to the same list object.

So what does copying a list mean?

Copying a python list means creating a new python object whose contents are identical.

The following figure shows what we want to achieve when we copy or clone a list.

In this article, we will discuss three different methods to copy a python list.

The first two methods can be used in python2 and python3 whereas the third one works for python3 only.

First: Copying by Slicing

The most common way (especially in python2) to copy a python list is to use slicing.

If you have been coding in python for a while, you probably came across some code that looks like this.

When you omit the start index and the end index from the slice, then your slice will start from the beginning of the list all the way to the end of the list.

And because slicing creates a new object, then the above code effectively copies or clones the whole list into another list.

Let’s go ahead and confirm this.

>>> a = [1, 2, 3, 7] >>> b = a[:] >>> b [1, 2, 3, 7] >>> id(a) 4440018888 >>> id(b) 4440454712

This code confirms two things:

1- the items of list b are the same as those of list a

2- a and b are different objects

But how do we know they are different?

One way is by observing that id(a) is different from id(b) .

If you don’t know what the id() function does, it basically returns the address of a python object in the memory.

Needless to say, two variables will refer to the same object only if the id of these two variable are exactly the same. Otherwise, they refer to different objects.

You want to be more assured?

Let’s try to modify a and see if b remains unchanged.

If b is modified, then a and b refer to the same object.

If b remains unchanged, then a and b refer to two separate objects.

>>> a = [1, 2, 3, 7] >>> b = a[:] >>> b [1, 2, 3, 7] >>> a[0] = -10 >>> a [-10, 2, 3, 7] >>> b [1, 2, 3, 7]

As you can see, after a was modified, b remains unchanged.

Awesome, we successfully copied a python list.

Second: Copying using list() function

Another way to create a copy of a list is to use the list() built-in function.

The list() function is used to create a list object from any iterable.

And most of the time in real code, this iterable is not a list.

For example, the following code creates a new list off of the items of a string.

>>> s = "hello" >>> l = list(s) >>> l ['h', 'e', 'l', 'l', 'o']

But since a list is an iterable itself, there is nothing that prevents you from creating a list from another list.

>>> a = [1, 2, 3, 4] >>> b = list(a) >>> b [1, 2, 3, 4] >>> id(a) 4354322312 >>> id(b) 4354377672

Even though this is not a common way to copy a list, it is still a valid one.

Third: Copying using the copy() Method

This is when Python3 comes to the rescue with a beautiful way to copy a list.

Python3 introduced a new method to lists called copy() and it does exactly what you think it does.

It copies a list into another list.

>>> a = [1, 2, 3, 4] >>> b = a.copy() >>> id(a) 4354356936 >>> id(b) 4354322312

The only downside is that it is not available in python2.

But if you are using python3, there is no debate this is the best, and most readable way to copy a list.

Conclusion

If you are using python2, you can copy a list by slicing or by using the list() function.

If you are using python3, use the list’s copy() method.

Learning Python?

Are you Beginning your Programming Career?

I provide my best content for beginners in the newsletter.

  • Python tips for beginners, intermediate, and advanced levels.
  • CS Career tips and advice.
  • Special discounts on my premium courses when they launch.

Источник

5 Ways to Copy a List in Python: Let’s Discover Them

Copy list in Python

It’s very common to copy a list in your Python programs. But, what should you absolutely know about copying lists?

How to copy a Python list?

Python provides multiple ways to copy a list depending on what your program needs to do with the existing list. You can use the assignment operator, the list copy method, the slice notation and shallow or deep copy.

This tutorial is designed to show you everything you need to know about copying lists in Python.

How to Make a Copy of a List in Python

I will start with a simple example to understand together how copying list works in Python.

After defining a list called numbers I use the assignment operator ( = ) to copy this list to a new list called new_numbers.

>>> numbers = [1,4,7,19,23] >>> new_numbers = numbers

Now I add a new element to the new_numbers list using the append method and verify the elements in both lists using the print function:

>>> new_numbers.append(34) >>> print(numbers) [1, 4, 7, 19, 23, 34] >>> print(new_numbers) [1, 4, 7, 19, 23, 34]

For some reason even if we have added the new number to the new_numbers list only, both of our lists contain the new number.

We will use the built-in id function to print the memory address of our two lists and to make it more readable we will also use the hex function that provides an hexadecimal representation of an integer.

>>> hex(id(numbers)) '0x10d75e5a0' >>> hex(id(new_numbers)) '0x10d75e5a0'

Both variables point to the same memory address, so numbers and new_numbers points to the same list object. That’s why we see the new element in both of them.

So, how can we copy our list to a completely new object?

How to Create An Actual Copy of the Original List

Python provides the list copy method that allows to create a new list object from the one we copy.

Let’s use the copy method on our original list to create the list new_numbers:

Now we will append a number to the new list we have created and we will verify that the number is not present in the original list:

>>> new_numbers.append(34) >>> print(numbers) [1, 4, 7, 19, 23] >>> print(new_numbers) [1, 4, 7, 19, 23, 34]

This time the original list has not been changed by the append method applied to the new list.

And as confirmation we will also verify the memory location of both list objects:

>>> hex(id(numbers)) '0x10751d460' >>> hex(id(new_numbers)) '0x10761d9b0'

Different memory addresses for the two objects. That’s good!

Copying Using the Python Slice Notation

Another way to copy a Python list is with the slice notation.

The slice notation can be used to copy parts of a list into a new list or even the entire list by simply using the following expression:

Let’s apply it to our numbers list:

After adding another number to the new list you can see that the original list, once again, is unchanged:

>>> new_numbers.append(34) >>> print(numbers) [1, 4, 7, 19, 23] >>> print(new_numbers) [1, 4, 7, 19, 23, 34]

And that with the slice notation we have created a new list object:

>>> hex(id(numbers)) '0x105e92460' >>> hex(id(new_numbers)) '0x105f925f0'

And also this one is done! 🙂

Shallow Copy Vs Deep Copy

The difference between a shallow copy and a deep copy only applies to compound objects, in other words to objects that contain other objects.

Examples of compound objects are class instances and lists.

The Python copy module allows to create shallow copies and deep copies of objects. Below you can see the syntax for both types of copy:

SHALLOW COPY: new_object = copy.copy(original_object) DEEP COPY: new_object = copy.deepcopy(original_object)

With a shallow copy a new compound object is created (e.g. a list of lists) and references to the objects found in the original object are added to the new compound object.

In the next section we will see exactly how a shallow copy works.

In the meantime I want to make clear the difference between a shallow copy and a deep copy.

A deep copy creates a new compound object (e.g. a list of lists) then it also creates copies of the objects found in the original object and inserts them in the new compound object.

The definitions of shallow copy and deep copy will be a lot clearer in the next sections where we will see how they work in practice.

How to Make a Shallow Copy in Python

Let’s see how a shallow copy works with a list…

…try these commands in your Python shell to make sure the behaviour of shallow and deep copying is clear to you:

>>> import copy >>> numbers = [[1,2,3], [4,5,6], [7,8,9]] >>> new_numbers = copy.copy(numbers)

If I add an element to the new_numbers list the original list doesn’t change:

>>> new_numbers.append([10,11,12]) >>> numbers [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> new_numbers [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

This confirms that in the shallow copy a new compound object has been created. In other words the new compound object is not a reference to the original object.

But now, let’s try to update one element common between the original and the new list:

>>> new_numbers[0][0] = 4 >>> numbers [[4, 2, 3], [4, 5, 6], [7, 8, 9]] >>> new_numbers [[4, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

I have updated the first element of the first list object in the original list.

As you can see the element has been updated in both lists, the original and the new one.

That’s because we have used a shallow copy and hence the first element of the new_numbers list is just a reference to the first element of the numbers list ([1,2,3]).

We are using cookies to give you the best experience on our website.

You can find out more about which cookies we are using or switch them off in settings .

Источник

Читайте также:  Структура данных queue java
Оцените статью