2

What I want to do is to copy some elements of one list-of-list to other based on certain conditions and then change the original list of lists

arr = [[1,0,4],[1,2,65],[2,3,56],[11,14,34]]
brr = []

for x in range(0,len(arr)):
    if arr[x][1] < 10:
        brr.append(arr[x])
        arr[x][1] = 1000
print(brr)

O/P:

[[1, 1000, 4], [1, 1000, 65], [2, 1000, 56]]

in the above example, I wanted to copy all the list with the middle element <10 to another list-of-list brr and then change the element in the original list to a large value. However, when I change a value in the original list it also changes the value in the second list

I know that when I append arr[i] to brr, brr just stores the reference pointers to the lists in arr and hence when the values at those addresses are changed it reflects at both the places,

also, if I had to copy the entire l-o-l I could have done it with deepcopy, but what is the best way to do it if there is a criteria /condition

Srini
  • 1,619
  • 1
  • 19
  • 34
  • Possible duplicate of [What exactly is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm) – Srini Mar 22 '19 at 19:16

3 Answers3

4

Here's another way of copying lists, along with a more pythonic way of iterating through a list

arr = [[1, 0, 4], [1, 2, 65], [2, 3, 56], [11, 14, 34]]
brr = []

for x in arr:
    if x[1] < 10:
        brr.append(list(x))
        x[1] = 1000
print(brr)
# [[1, 0, 4], [1, 2, 65], [2, 3, 56]]
Danielle M.
  • 3,607
  • 1
  • 14
  • 31
3
from copy import deepcopy
#....
brr.append(deepcopy(arr[x]))
CristiFati
  • 38,250
  • 9
  • 50
  • 87
Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
  • Doesn't `deepcopy` take an argument? Also don't you invoke it like `copy.deepcopy()` ? Do lists have a `deepcopy` fn ? – Srini Mar 22 '19 at 19:15
3

You should create a deep copy of each (inner) list from arr that you want to copy. One way (which is the shortest to write, as there are numerous: check [SO]: How to clone or copy a list?), is via slicing:

Translated to your code, you should replace

brr.append(arr[x])

by

brr.append(arr[x][:])

Note: If you want to be generic / scalable, you should go for copy.deepcopy, as it would also work if one of arr[x]'s elements wold be itself a list (which currently isn't the case).

CristiFati
  • 38,250
  • 9
  • 50
  • 87