Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid syntax python starred expressions

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?

like image 340
user2385591 Avatar asked May 15 '13 11:05

user2385591


People also ask

How do I fix invalid syntax in Python?

Defining and Calling Functions You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

What is starred expression in Python?

The starred expression will create a list object, although we start with a tuple object. Starred expressions can be used with more than just tuples, and we can apply this technique for other iterables (e.g., lists, strings).

Why does Python keep saying invalid syntax?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.

What does invalid syntax Pyflakes E mean?

i wrote the above code,and the error was syntax error , it took me about an hour to figure out that my fullstop was outside the quotes. so in my own opinion, pyflakes E syntax error actually mean syntax error; you just have to check your code again.


1 Answers

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.

like image 108
Martijn Pieters Avatar answered Oct 29 '22 03:10

Martijn Pieters