What is the best way to copy a list? [duplicate]

What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?

lst = ['one', 2, 3]

lst1 = list(lst)

lst2 = lst[:]

import copy
lst3 = copy.copy(lst)

Asked by: Madaline529 | Posted: 28-01-2022

Answer 1

If you want a shallow copy (elements aren't copied) use:


If you want to make a deep copy then use the copy module:

import copy

Answered by: Darcy818 | Posted: 01-03-2022

Answer 2

I often use:

lst2 = lst1 * 1

If lst1 it contains other containers (like other lists) you should use deepcopy from the copy lib as shown by Mark.

UPDATE: Explaining deepcopy

>>> a = range(5)
>>> b = a*1
>>> a,b
([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
>>> a[2] = 55 
>>> a,b
([0, 1, 55, 3, 4], [0, 1, 2, 3, 4])

As you may see only a changed... I'll try now with a list of lists

>>> a = [range(i,i+3) for i in range(3)]
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>> b = a*1
>>> a,b
([[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[0, 1, 2], [1, 2, 3], [2, 3, 4]])

Not so readable, let me print it with a for:

>>> for i in (a,b): print i   
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>> a[1].append('appended')
>>> for i in (a,b): print i

[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]
[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]

You see that? It appended to the b[1] too, so b[1] and a[1] are the very same object. Now try it with deepcopy

>>> from copy import deepcopy
>>> b = deepcopy(a)
>>> a[0].append('again...')
>>> for i in (a,b): print i

[[0, 1, 2, 'again...'], [1, 2, 3, 'appended'], [2, 3, 4]]
[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]

Answered by: Daryl130 | Posted: 01-03-2022

Answer 3

You can also do:

a = [1, 2, 3]
b = list(a)

Answered by: Dainton961 | Posted: 01-03-2022

Answer 4

I like to do:

lst2 = list(lst1)

The advantage over lst1[:] is that the same idiom works for dicts:

dct2 = dict(dct1)

Answered by: Darcy122 | Posted: 01-03-2022

Answer 5

Short lists, [:] is the best:

In [1]: l = range(10)

In [2]: %timeit list(l)
1000000 loops, best of 3: 477 ns per loop

In [3]: %timeit l[:]
1000000 loops, best of 3: 236 ns per loop

In [6]: %timeit copy(l)
1000000 loops, best of 3: 1.43 us per loop

For larger lists, they're all about the same:

In [7]: l = range(50000)

In [8]: %timeit list(l)
1000 loops, best of 3: 261 us per loop

In [9]: %timeit l[:]
1000 loops, best of 3: 261 us per loop

In [10]: %timeit copy(l)
1000 loops, best of 3: 248 us per loop

For very large lists (I tried 50MM), they're still about the same.

Answered by: Lenny260 | Posted: 01-03-2022

Answer 6

You can also do this:

import copy
list2 = copy.copy(list1)

This should do the same thing as Mark Roddy's shallow copy.

Answered by: Jack928 | Posted: 01-03-2022

Answer 7

In terms of performance, there is some overhead to calling list() versus slicing. So for short lists, lst2 = lst1[:] is about twice as fast as lst2 = list(lst1).

In most cases, this is probably outweighed by the fact that list() is more readable, but in tight loops this can be a valuable optimization.

Answered by: Victoria449 | Posted: 01-03-2022

Similar questions

What is the best way to call Java code from Python?

I have a Java class library (3rd party, proprietary) and I want my python script to call its functions. I already have java code that uses this library. What is the best way to achieve this?

python - How to best use GPS data?

I am currently developing an application that receives GPS data gathered using and android phone. I need to analyze that data in terms of speed, acceleration, etc... My question is: Can I trust the speed values returned by the phone? Or should I use the difference in position and time between two points to get the values I want? Also, is there any "standard" method for filtering input data? Or any library (python w...

python - best way to find out type

I have a dict val_dict - {'val1': 'abcd', 'val': '1234', 'val3': '1234.00', 'val4': '1abcd 2gfff'} All the values to my keys are string. So my question is how to find out type for my values in the dict. I mean if i say`int(val_dict['val1']) will give me error. Basically what I am trying to do is find out if the string is actual string or int or float.`

python - Best way not to run out of list index

Let's say I have 2D list and I want to do a check if previous/next element equals something. What is the best way to make sure that I will not access list[-1][-1] or list[len + 1][len + 1]? Here's an example of what I'm trying to do: if list[y + 1][x] == value and list[y - 1][x] == value: do something elif list[y][x + 1] == value and list[y][x - 1] == value: do some...

python - What is the best way to sort this list?

I have the following list: my_list = ['name.13','name.1', 'name.2','name.4', 'name.32'] And I would like sort the list and print it out in order, like this name.1 name.2 name.4 name.13 name.32 What I have tried so far is: print sorted(my_list) name.1 name.13 name.2 name.32 name.4 The sorted() command obviously treats the ...

python - Best way to add a "+" and "-"?

What is the best way to display either a + in front, for a float? Lets say if a user inputs the number "10". I want to have a "+" appear in front of it since it is a positive number. If it were a negative number then I would leave it as it is. Would I have to use an if statement and then convert it to a string and then add in the + sign? Or is there an easier way?

python - Best way to test if file available via URL?

I'm writing a script to DL the entire collection of BBC podcasts from various show hosts. My script uses BS4, Mechanize, and wget. I would like to know how I can test if a request for a URL yields a response code of '404' form the server. I have wrote the below function: def getResponseCode(br, url): print("Opening: " + url) try: response = br.open(url) print("Response code: ...

python - Best way to deal with xyz data

I am new to python, and am trying to work out the best way to approach a data analysis problem. Apologies if this question seems basic. I essentially want help in working out whether I want to use tuples, dicts or a pandas dataframe to store my data. Here is my scenario: My data: I have a 3D spatial dataset, with data at uneven XYZ positions. The precise position of the data points is vital, so I can't resample t...

python - Best way to obtain information from a dict

I have a dict with "multiple layers" (I don't really know how to call it) and I would like to only use few information from it. So heres the dict: {'userTimestamp': 1, 'user': {'id': '20', 'links': {'self': [{'href': 'https://john.com'}]}, 'mail': 'john@john.com', 'message': 'Hello world', 'name': 'john'} } Now I somehow want to go through the dict...

Best ways to do ssh and scp in Python?

What are the best ways to do ssh and scp in Python? I want to eliminate an Apache Ant build like we are doing in Java.

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

python - How do I turn an RSS feed back into RSS?

According to the feedparser documentation, I can turn an RSS feed into a parsed object like this: import feedparser d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml') but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XM...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python