[Python-Dev] syntactic shortcut - unpack to variably sized list

"Martin v. Löwis" martin at v.loewis.de
Sat Nov 13 12:41:12 CET 2004


Johan Hahn wrote:
> Hi
> 
> As far as I can tell from the archive, this has not been discussed before.
> This is the second time in less than a week that I have stumbled over the rather 
> clumsy syntax of extracting some elements of a sequence and at the same time 
> remove those from the sequence:
> 
>>>>L = 'a b 1 2 3'.split(' ')
>>>>a,b,L = L[0], L[1], L[2:]

As James says, this has been discussed before. Typically, you don't need
the rest list, so you write

a,b = 'a b 1 2 3'.split(' ')[:2]

If you do need the rest list, it might be best to write

L = 'a b 1 2 3'.split(' ')
a = L.pop(0)
b = L.pop(0)

Whether this is more efficient than creating a new list depends on the
size of the list; so you might want to write

L = 'a b 1 2 3'.split(' ')
a = L[0]
b = L[1]
del L[:2]

This is entirely different from functions calls, which you simply cannot
spread over several statements.

Regards,
Martin


More information about the Python-Dev mailing list