wogsland
wogsland

Reputation: 9508

When is full list slice used?

So I understand that if I have a list like

>>> dinner = ['steak', 'baked potato', 'red wine']

then the slice with unspecified beginning and endpoints is the whole list

>>> dinner[:]
['steak', 'baked potato', 'red wine']

My question is if this full list slice is ever used in practice, and, if so, what is the use case for it? Why not just reference the list dinner without the slice notation [:]?

Upvotes: 1

Views: 48

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78546

If used on the LHS of the assignment operator, a full list slice is used to mutate a list in-place:

>>> dinner = ['steak', 'baked potato', 'red wine']
>>> dinner[:] = ['pasta']
>>> dinner
['pasta']

Otherwise, a full list slice usually comes handy when you need to modify/mutate the original list, say in a loop, and you need to keep a reference copy, more approriately called a shallow copy:

for i in dinner[:]:
    # mutate dinner without running into problems

This allows the behavior of the for loop to be consistent with the state of the original list.

You could also create a shallow copy by using copy.copy or calling list on the original list, but [:] is more generally used, being a language construct and also less verbose.

Upvotes: 3

wim
wim

Reputation: 362567

A full list slice is the usual Python syntax to make a shallow copy of a list.

>>> dinner = ['steak', 'baked potato', 'red wine']
>>> dinner1 = dinner  # just another reference to the original object
>>> dinner2 = dinner[:]  # makes a new object
>>> dinner[0] = 'spam'
>>> dinner1  # dinner1 reflects the change to dinner
['spam', 'baked potato', 'red wine']
>>> dinner2  # dinner2 doesn't reflect the change to dinner
['steak', 'baked potato', 'red wine']

If you just reference the original list without a slice, you will also see changes to the original list in your new reference. That's sometimes what you want, and sometimes not what you want.

Upvotes: 4

Related Questions