Can an if statement in a list comprehension use an else?

What you said…

no else?  =>  if after for
else?     =>  if and else before for
1 Like

Noted, thank you! Didn’t expect an answer so soon. :slight_smile:

1 Like

hey everyone,

I know this must be old topic for you but I am having trouble with loops so i wanted to ahead ask about the can_ride_coaster code. Can somebody explain to me where my code went wrong and how i may fix with this if /else statement ? So basically I can get the list printed but not append it to can_ride_coaster
Thanks very much!


can_ride_coaster =

for height in heights:
if height < 161:
continue

else:
new_list = print(height)
new_list.append(can_ride_coaster)

That is the new list to which those eligible rider heights will be appended.

can_ride_coaster.append(height)

Work with that hint and see if you can modify your code to suit.

1 Like

I believe your confusion is because the example provided in the lesson uses very similar temporary and list variable.

usernames = [word for word in words if word[0] == '@']

I have just modified the above one in the following way… May I know why is it showing error:

divbythree = [ x for x in range(1,20) if x % 3 == 0 print(“yes”)

else print(“No”) ]

print(divbythree)

Like a normal if statement you need a valid expression following if. Your code would be like writing the following which is not valid syntax.

if x % 3 == 0 print("yes"):

I’d advise against adding side effects like printing to stdout within a list comprehension in general even in cases where you can get away with it. Stick with a for loop for that kind of thing, it’s just not what comprehensions are for.

1 Like

3 posts were merged into an existing topic: FAQ: Function Arguments: *args and **kwargs - Variable number of arguments: *args

Hello,

Can someone explain why the following is incorrect?

Is it because “if” is what only accepts inequalities in Python?

can_ride_coaster = [tall for tall > 161 in heights]

Hello,

Can someone explain why the following is incorrect?

Is it because “if” is what only accepts inequalities in Python?

can_ride_coaster = [tall for tall > 161 in heights]

can_ride_coaster = tall for tall _________ what was the original list? it was ‘heights’ and we need to say ‘in’ since its a loop
_________> 161 in heights Yeah we need an if logic here, but what should be > 161? use your tall variable

So it would be like…
can_ride_coaster = [tall for tall in heights if tall > 161 ]

And then you want to print it.

print (can_ride_coaster)

The above will give a syntax error, so cannot be written that way.

You are correct that it would be,

... [tall for tall in heights if tall > 161]