I’m writing a program and I have a problem: I want to create two lists, one of which is reversed. The problem is that the two lists are intertwined and I don’t want that. Code:
a = [[[]], [[0.4, 2]], [[0.8, 1]]]
b = [i for i in reversed(a)]
#a = [[[]], [[0.4, 2]], [[0.8, 1]]] and b = [[[0.8, 1]], [[0.4, 2]], [[]]]
b[0][0][1] = 100
#b = [[[0.8, 100]], [[0.4, 2]], [[]]]
#a = [[[]], [[0.4, 2]], [[0.8, 100]]]
I want when I change b, a not to be changed. Thanks.
you want to create a deep copy of a
import copy
a = [[[]], [[0.4, 2]], [[0.8, 1]]]
b = copy.deepcopy(list(reversed(a)))
when you just copied the sublists of a you just copied them by reference, both a and b had the same lists inside of them
While you can use deepcopy, if the layout of the list is always the same and known to you, it is probably considerably faster to "manually" copy the lists, in particular if the lists are very large.
>>> a = [[[random.random() for _ in range(random.randint(0, 10))]] for _ in range(100)]
>>> b = copy.deepcopy(list(reversed(a)))
>>> c = [list(map(list, x)) for x in reversed(a)]
>>> a[::-1] == b == c
True
>>> %timeit copy.deepcopy(list(reversed(a)))
1000 loops, best of 3: 375 µs per loop
>>> %timeit [list(map(list, x)) for x in reversed(a)]
10000 loops, best of 3: 35.5 µs per loop
(I remember the question having been tagged as "machine learning", so this might be relevant.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With