Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

4 of 5
'or' instead of 'of'
Jakube
  • 22k
  • 3
  • 28
  • 108

Extended iterable unpacking ("Starred assignment", Python 3 only)

The best way to explain this is via an example:

>>> a,*b,c=range(5)
>>> a
0
>>> b
[1, 2, 3]
>>> c
4

We've already seen a use for this — turning an iterable into a list in Python 3:

a=list(range(10))
*a,=range(10)

Here are a few more uses.

Getting the last element from a list

a=L[-1]
*_,a=L

In some situations, this can also be used for getting the first element to save on parens:

a=(L+[1])[0]
a,*_=L+[1]

Assigning an empty list and other variables

a=1;b=2;c=[]
a,b,*c=1,2

Removing the first or last element of a non-empty list

_,*L=L
*L,_=L

These are shorter than the alternatives L=L[1:] and L.pop(). The result can also be saved to a different list.

Tips courtesy of @grc

Sp3000
  • 62.2k
  • 13
  • 117
  • 292

AltStyle によって変換されたページ (->オリジナル) /