Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list slicing and direct assignment from list?

Tags:

python

I've been wondering if there is any difference "behind the scenes" between:

a=[1,2,3]
a[0], a[1], a[2] = a[2], a[1], a[0]

and:

a = [1,2,3]
a[0:2] = a[2::-1]

Both of these change the original list in memory, and as far as I can tell do the same thing, but I've been wondering if, for example, the first is more memory efficient because it doesn't need to create Slice objects or something like that.

like image 287
Nescio Avatar asked Dec 11 '25 22:12

Nescio


1 Answers

The complexity of list indexing and slicing is O(N) and when you use multiple indexing actually you used multiple script with O(N) order. While you can do that with one step using slicing.Also using slicing is more straight and elegant than multiple indexing.

So it's better to use slicing which is more pythonic rather than indexing.

a[0:2] = a[2::-1]
like image 118
Mazdak Avatar answered Dec 13 '25 13:12

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!