Nescio
Nescio

Reputation: 513

Difference between list slicing and direct assignment from list?

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.

Upvotes: 3

Views: 111

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

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]

Upvotes: 3

Related Questions