Quantcast
Channel: How do I clone a list so that it doesn't change unexpectedly after assignment? - Stack Overflow
Viewing all articles
Browse latest Browse all 117

Answer by SCB for List changes unexpectedly after assignment. Why is this and how to prevent it?

$
0
0

It surprises me that this hasn't been mentioned yet, so for the sake of completeness...

You can perform list unpacking with the "splat operator": *, which will also copy elements of your list.

old_list = [1, 2, 3]new_list = [*old_list]new_list.append(4)old_list == [1, 2, 3]new_list == [1, 2, 3, 4]

The obvious downside to this method is that it is only available in Python 3.5+.

Timing wise though, this appears to perform better than other common methods.

x = [random.random() for _ in range(1000)]%timeit a = list(x)%timeit a = x.copy()%timeit a = x[:]%timeit a = [*x]#: 2.47 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)#: 2.47 µs ± 54.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)#: 2.39 µs ± 58.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)#: 2.22 µs ± 43.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Viewing all articles
Browse latest Browse all 117

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>