If slicing does not create a copy of a list nor does list() how can I get a real copy of my list?

I am trying to modify a list and since my modifications were getting a bit tricky and my list large I took a slice of my list using the following code

tempList=origList[0:10]
for item in tempList:
    item[-1].insert(0 , item[1])
    del item[1]

I did this thinking that all of the modifications to the list would affect tempList object and not origList objects.

Well once I got my code right and ran it on my original list the first ten items (indexed 0-9) were affected by my manipulation in testing the code printed above.

So I googled it and I find references that say taking a slice copies the list and creates a new-one. I also found code that helped me find the id of the items so I created my origList from scratch, got the ids of the first ten items. I sliced the list again and found that the ids from the slices matched the ids from the first ten items of the origList.

I found more notes that suggested a more pythonic way to copy a list would be to use

tempList=list(origList([0:10])

I tried that and I still find that the ids from the tempList match the ids from the origList.

Please don't suggest better ways to do the coding-I am going to figure out how to do this in a list Comprehension on my own after I understand what how copying works

Based on Kai's answer the correct method is:

import copy
tempList=copy.deepcopy(origList[0:10])
id(origList[0])
>>>>42980096
id(tempList[0])
>>>>42714136

Works like a charm


Asked by: Emma738 | Posted: 06-12-2021






Answer 1

Slicing creates a shallow copy. In your example, I see that you are calling insert() on item[-1], which means that item is a list of lists. That means that your shallow copies still reference the original objects. You can think of it as making copies of the pointers, not the actual objects.

Your solution lies in using deep copies instead. Python provides a copy module for just this sort of thing. You'll find lots more information on shallow vs deep copying when you search for it.

Answered by: Miller304 | Posted: 07-01-2022



Answer 2

If you copy an object the contents of it are not copied. In probably most cases this is what you want. In your case you have to make sure that the contents are copied by yourself. You could use copy.deepcopy but if you have a list of lists or something similar i would recommend using copy = [l[:] for l in list_of_lists], that should be a lot faster.

A little note to your codestyle:

  • del is a statement and not a function so it is better to not use parens there, they are just confusing.
  • Whitespaces around operators and after commas would make your code easier to read.
  • list(alist) copies a list but it is not more pythonic than alist[:], I think alist[:] is even more commonly used then the alternative.

Answered by: Dominik372 | Posted: 07-01-2022



Similar questions

python - Slicing arrays in Numpy / Scipy

I have an array like: a = array([[1,2,3],[3,4,5],[4,5,6]]) What's the most efficient way to slice out a 1x2 array out of this that has only the first two columns of "a"? i.e. array([[2,3],[4,5],[5,6]]) in this case.


Slicing python lists

If I have a list of say 'n' elements (each element is a single byte ) which represents a rectangular 2d matrix, how can I split this into rectangles of say w * h, starting from the first element of the list , just using the python standard functions for example l = [ 1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15....20. 21,22,23,24,25....30 ..... .................200]


python - Django paging with slicing

I'm new to Django and Python and I'm trying to understand how to accomplish paging without getting all the records from a QuerySet first. All the examples I've seen with QuerySets will get all the records first like below. tickets = Ticket.objects.filter(site=site.id) paginator = Paginator(tickets, settings.PAGE_SIZE) This seems to make sense so that the Paginator will have a referenc...


python - Slicing a 2D numpy array into a 1D array

I have a 2D numpy array, FilteredOutput, that has 2 columns and 10001 rows, though the number of rows is a variable. I am trying to take the 2nd column of FilteredOutput and use it to populate a new 1D numpy array called timeSeriesArray using some code I found


python - slicing a 2d numpy array

The following code: import numpy as p myarr=[[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6]] copy=p.array(myarr) p.mean(copy)[:,1] Is generating the following error message: Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> p.mean(copy)[:,1] IndexError: 0-d arrays can onl...


Slicing with python on a single line

I have data "line" FF= ['123451234512345678901234512345', '123451234512345678901234512345'] I need to slice line 1-5, 6-10, 11, 12-22. How do I slice? data= [] for col in FF: data.append(col)


add days to a date in Python using loops, ranges, and slicing

I'm a beginner in python and I've recently learned how to do the basics of: functions, loops, ranges, for/if statements, and string slicing. So far I have: date = raw_input("Enter the date checked out in YYYY-MM-DD format: ") dueDate = raw_input("Book is due:") length = len(date) counter=0 for i in range(length): if date[i] == "-": counter = counter + 1 if 1 < counter &...


Slicing in python similar to MATLAB

In Matlab, slice can be a vector: a = {'a','b','c','d','e','f','g'}; % cell array b = a([1:3,5,7]); How can I do the same thing in python? a = ['a','b','c','d','e','f','g'] b = [a[i] for i in [0,1,2,4,6]] but when 1:3 becomes 1:100, this will not work. Using range(2),4,6 returns ([0,1,2],4,6), not (0,1,2,4,6). Is there a fast and "pythonic" way?


python numpy array slicing

I have an 2d array, A that is 6x6. I would like to take the first 2 values (index 0,0 and 0,1) and take the average of the two and insert the average into a new array that is half the column size of A (6x3) at index 0,0. Then i would get the next two indexes at A, take average and put into the new array at 0,1. The only way I know how to do this is using a double for loop, but for performance purposes (I will be ...


Slicing url with Python

Hi how to use python to transform the url of a article to it's print url. article url:http://www.indianexpress.com/news/second-time-as-farce/800228/0 print url:http://www.indianexpress.com/story-print/800228/ How to convert article url to print url?


python - Slicing at runtime

can someone explain me how to slice a numpy.array at runtime? I don't know the rank (number of dimensions) at 'coding time'. A minimal example: import numpy as np a = np.arange(16).reshape(4,4) # 2D matrix targetsize = [2,3] # desired shape b_correct = dynSlicing(a, targetsize) b_wrong = np.resize(a, targetsize) print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] print b_correct [...


python - Slicing arrays in Numpy / Scipy

I have an array like: a = array([[1,2,3],[3,4,5],[4,5,6]]) What's the most efficient way to slice out a 1x2 array out of this that has only the first two columns of "a"? i.e. array([[2,3],[4,5],[5,6]]) in this case.


Slicing python lists

If I have a list of say 'n' elements (each element is a single byte ) which represents a rectangular 2d matrix, how can I split this into rectangles of say w * h, starting from the first element of the list , just using the python standard functions for example l = [ 1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15....20. 21,22,23,24,25....30 ..... .................200]


python - Django paging with slicing

I'm new to Django and Python and I'm trying to understand how to accomplish paging without getting all the records from a QuerySet first. All the examples I've seen with QuerySets will get all the records first like below. tickets = Ticket.objects.filter(site=site.id) paginator = Paginator(tickets, settings.PAGE_SIZE) This seems to make sense so that the Paginator will have a referenc...


Slicing a string in Python

When we need to slice a string at a particular location, we need to know the index from where we want to. For example, in the string: >>> s = 'Your ID number is: 41233' I want to slice the string starting from : and get the number. Sure I can count at what index : is and then slice, but is that really a good approach? Of...


python - Slicing a 2D numpy array into a 1D array

I have a 2D numpy array, FilteredOutput, that has 2 columns and 10001 rows, though the number of rows is a variable. I am trying to take the 2nd column of FilteredOutput and use it to populate a new 1D numpy array called timeSeriesArray using some code I found


python - slicing a 2d numpy array

The following code: import numpy as p myarr=[[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6]] copy=p.array(myarr) p.mean(copy)[:,1] Is generating the following error message: Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> p.mean(copy)[:,1] IndexError: 0-d arrays can onl...


Slicing with python on a single line

I have data "line" FF= ['123451234512345678901234512345', '123451234512345678901234512345'] I need to slice line 1-5, 6-10, 11, 12-22. How do I slice? data= [] for col in FF: data.append(col)


add days to a date in Python using loops, ranges, and slicing

I'm a beginner in python and I've recently learned how to do the basics of: functions, loops, ranges, for/if statements, and string slicing. So far I have: date = raw_input("Enter the date checked out in YYYY-MM-DD format: ") dueDate = raw_input("Book is due:") length = len(date) counter=0 for i in range(length): if date[i] == "-": counter = counter + 1 if 1 < counter &...


Slicing in python similar to MATLAB

In Matlab, slice can be a vector: a = {'a','b','c','d','e','f','g'}; % cell array b = a([1:3,5,7]); How can I do the same thing in python? a = ['a','b','c','d','e','f','g'] b = [a[i] for i in [0,1,2,4,6]] but when 1:3 becomes 1:100, this will not work. Using range(2),4,6 returns ([0,1,2],4,6), not (0,1,2,4,6). Is there a fast and "pythonic" way?






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



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



top