Question

Why does the following code throw a SyntaxError for *phones in Python 2.7.3?

contact = ('name', 'email', 'phone1', 'phone2')
name, email, *phones = contact

Was this introduced in Python 3 and not backported? How can I get this to work in Python 2? That is, if there isn't some trivial way to fix things here.

Was it helpful?

Solution

Yup, the extended unpacking syntax (using * to take the rest) is Python 3.x only. The closest you can get in Python 2.x is explicitly slicing the parts you want from the remainder:

contact = ('name', 'email', 'phone1', 'phone2')
(name, email), phones = contact[:2], contact[2:]

If you needed it to work on arbitrary iterables, then you can use something like:

from itertools import islice
i = iter(contact)
(name, email), phone = tuple(islice(i, 2)), list(i)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top