0
list = sorted(set(list))
list[:] = sorted(set(list))
list[::] = sorted(set(list))

I am new to Python, and the first thing I am noticing is that the syntax is concise, but non obvious.

For example, it is not clear what is going on in the three statements above. I ran them and got some results and seems like statement 1 is not updating the list, while statement 2 and statement 3 are. But, I am sure there is more going on here.

What do each of the above assignments mean?

Lazer
  • 90,700
  • 113
  • 281
  • 364
  • This is absolutely a duplicated question but I forget which question it is duplicated with ... Could someone help to flag as duplicated? – Sraw Jan 09 '18 at 05:55

1 Answers1

3

2 and 3 do the same (the step argument of a slice is optional, and both these slices use the default step of 1), but they both are inherently different from 1. Slice assignment (lst[:] = ...) mutates the original object while a common assignment (lst = ...) rebinds the variable to a new object.

>>> lst = [3,3,2,2,1,1]
>>> id(lst)
139793325565704
>>> lst[:] = sorted(set(lst))
>>> lst
[1, 2, 3]
>>> id(lst)
139793325565704  # same object
>>> lst = sorted(set(lst))
>>> id(lst)
139793325524744  # different object

A point worth noting is that slice assignment can have any iterable on the rhs (for partial slices their number of elements must match the length of the slice):

>>> lst = [1,2,3]
>>> lst[1:] = 'ab'
>>> lst
[1, 'a', 'b']

See some of the slice docs for more detailed information.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks, any difference b/w using `[:]` vs `[::]`? – Lazer Jan 09 '18 at 05:55
  • No, not to my kowledge, they both set the `step` arg to `1`. – user2390182 Jan 09 '18 at 05:57
  • They are exactly the same @Lazer -- Slice notation goes `obj[start:stop:step]` or `obj[start:stop]` when omitted, start and stop are implied to be the beginning and end of the sequence respectively. When `step` is omitted, it's implied to be `1` – sytech Jan 09 '18 at 05:58