Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How remove the intrication between two reversed list in Python?

Tags:

python

list

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.

like image 393
Antoine MARTEL Avatar asked Feb 16 '26 18:02

Antoine MARTEL


2 Answers

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

like image 172
Derte Trdelnik Avatar answered Feb 19 '26 09:02

Derte Trdelnik


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.)

like image 27
tobias_k Avatar answered Feb 19 '26 08:02

tobias_k