David
David

Reputation: 195

All slice operations return a new list?

In Python Tutorials, it is said "All slice operations return a new list containing the requested elements".

>>>a = ['spam', 'eggs', 100, 1234]
>>>a[0:2] = [1, 12]
>>> a
[1, 12, 100, 1234]

If all slice operations return a new list, how could the list a get changed in this example? It seems like only slice operations on the right hand return a new list.

UPDATE

I mean what exactly a[:] is in Python, a reference to a new list or a reference to some part of list a or anything else. I'm interested in the base level implementation not the behavior.

Upvotes: 1

Views: 114

Answers (2)

aIKid
aIKid

Reputation: 28242

This is slicing:

b = a[0:2]

And this, is slice assigment:

a[0:2] = b

They're different. The latter will replace a slice part of a with the value of b. They look really similar, but different in use.

Upvotes: 4

user2486495
user2486495

Reputation: 1729

'=' is for assignment. And you are providing the locations in square brackets.

Upvotes: 1

Related Questions