pineappleexpress
pineappleexpress

Reputation: 27

for loop in return statement

I have a problem with this piece of code:

List=[' ', 'X', 'X', 'X']+[' ']*6
le='X'
def Return():
    return((for i in range(1, 10, 3):
        (List[i]==le and List[i+1]==le and List[i+2]==le)))

I wanted to write it with a for-loop instead of having to specify like this:

 def Return():
    return ((List[1]==le and List[2]==le and List[3]==le) or #True
        (List[4]==le and List[5]==le)...etc.)

When I use the foor-loop I just get a message saying "invalid syntax", but I don't get why.

Upvotes: 0

Views: 1574

Answers (3)

Antoine
Antoine

Reputation: 1070

You could use what is called "List comprehensions":

def Return():
    return any([List[i]==le and List[i+1]==le and List[i+2]==le for i in range(1, 10, 3)])

Upvotes: 2

sundar nataraj
sundar nataraj

Reputation: 8702

you can try using any

lis=[' ', 'X', 'X', 'X']+[' ']*6
le='X'
def func():
    return any(all(lis[j]==le for j in range(i,i+3)) for i in range(0,len(lis),3)

Note: Never use the python keywords as method names and variables

Upvotes: 1

unwind
unwind

Reputation: 400079

That's because for in Python isn't an expression, it has no value that you can return.

Upvotes: 1

Related Questions