Leo
Leo

Reputation: 1777

Strange SyntaxError: invalid syntax after defining statement in return

I have read alot of strange syntaxerror questions and have not seen mine among it yet and I am really at a loss. I am doing some homework for which the deadline is coming closer and this error I cant get rid of:

def create_voting_dict():
    strlist = [voting_data[i].split() for i in range(len(voting_data))]
    return voting_dict = {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist[h]))] for h in range(len(strlist))}

Which gets me the error:

return voting_dict = {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist[h]))] for h in range(len(strlist))}
                                                                                        ^         
SyntaxError: invalid syntax

This error did not occur when I defined voting_dict inside the procedure, but I need to define it globally so i put it after return and then I got the error. Have been counting parenthesis all over but that doesnt seem to be the problem.

I am sure that when I see the problem it is very easy, but I just dont see it. Thanks for any help.

*voting data is a list with strings and I made the procedure to split the strings and create a dictionary

Upvotes: 0

Views: 2431

Answers (3)

Mario Rossi
Mario Rossi

Reputation: 7799

If you want to create/populate a global variable voting_dict, then do:

def create_voting_dict():
    strlist= [voting_data[i].split() for i in range(len(voting_data))]
    global voting_dict
    voting_dict= {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist))}

create_voting_dict()

or

def create_voting_dict():
    strlist= [voting_data[i].split() for i in range(len(voting_data))]
    return {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist))}

voting_dict= create_voting_dict()

or even

def create_voting_dict(vd):
    strlist= [vd[i].split() for i in range(len(vd))]
    return {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist))}

voting_dict= create_voting_dict(voting_data)

The advantage of the later is that it's more general and thus can be used in other situations.

Upvotes: 1

Keval Doshi
Keval Doshi

Reputation: 748

Its problem with your return statement in which you cannot carry out assignments. Just do it a step before.

Upvotes: 1

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

You cannot define in a return. (Because assignments do not return values) Just do

return {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist[h]))] for h in range(len(strlist))}

Or define a voting_dict in a new statement and then return voting_dict.

See the example -

>>> def test():
        return num = 2
SyntaxError: invalid syntax
>>> def test():
        return 2

Upvotes: 6

Related Questions