Haomin Zeng
Haomin Zeng

Reputation: 69

python - invalid syntax when I use *

I created a simple function to unpack N elements from an iterable.

def drop_first_last(grades):
    grades = first, *middle, last
    return avg(middle)

When I run this function occurred following error:

grades = first, *middle, last

SyntaxError: invalid syntax

I don't know why this error occurred, how to fix it?

Upvotes: 2

Views: 290

Answers (2)

Peter Westlake
Peter Westlake

Reputation: 5036

The reason for the error is that this isn't Python syntax! The * notation is used to declare variable numbers of arguments and to unpack tuples. You are trying to use it to do something like the pattern matching found in functional languages like Haskell. Plus the assignment is backwards, as @thegrinner noted.

Upvotes: 0

Colin Bernet
Colin Bernet

Reputation: 1394

Just do:

middle = grades[1:-1]
return avg(middle)     

Upvotes: 7

Related Questions