Invalid syntax python starred expressions

user2385591 picture user2385591 · May 15, 2013 · Viewed 9.6k times · Source

I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet

 >>> record = ('Dave', '[email protected]', '773-555-1212', '847-555-1212')
 >>> name, email, *phone-numbers = record
 SyntaxError: invalid syntax
 >>>

Please explain. Is there any other way of doing the same?

Answer

Martijn Pieters picture Martijn Pieters · May 15, 2013

You are using Python 3 specific syntax in Python 2.

The * syntax for extended iterable unpacking in assignments is not available in Python 2.

See Python 3.0, new syntax and PEP 3132.

Use a function with * splat argument unpacking to simulate the same behaviour in Python 2:

def unpack_three(arg1, arg2, *rest):
    return arg1, arg2, rest

name, email, phone_numbers = unpack_three(*user_record)

or use list slicing.