Can you use if statements in list comprehension?

Python List Comprehension is used to create Lists. While generating elements of this list, you can provide condition that could be applied on the input lists to list comprehension.

In this tutorial, we will learn how to apply an if condition on input list[s] in List Comprehension.

Syntax

Following is the syntax of List Comprehension with IF Condition.

output = [ expression for element in list_1 if condition ]

where condition is applied, and the element [evaluation of expression] is included in the output list, only if the condition evaluates to True.

Example 1: List Comprehension using IF Condition

In this example, we shall create a new list from a list of integers, only for those elements in the input list that satisfy a given condition.

Python Program

list_1 = [7, 2, 6, 2, 5, 4, 3] list_2 = [ x * x for x in list_1 if [x % 2 == 0] ] print[list_2] Run

We have taken a list of integers. Then using list comprehension, we are generating a list containing squares of the elements in the input list, but with a condition that only if the element in input list is even number.

Output

[4, 36, 4, 16]

Example 2: List Comprehension using IF Condition and Multiple Input Lists

In this example, we shall create a new list from two lists of integers with a given condition.

Python Program

list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [ x * y for x in list_1 for y in list_2 if [x+y]%2 == 0 ] print[list_3] Run

Output

[5, 8, 12, 15]

Summary

In this tutorial of Python Examples, we learned how to use List Comprehension with an IF Condition in it.

We can use list comprehension using if without else in Python.

num = [i for i in range[10] if i>=5] print[num]

Python Example list comprehension if without else

Simple example code compares 2 iterable and prints the items which appear in both iterable.

a = [1, 2, 3, 4, 5] b = [5, 2, 3] res = [y for y in a if y in b] print[res]

Output:

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

Answer: Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension. The if/else is placed in front of them for a component of the list comprehension.

res = ["Yes" if num % 3 == 0 else "No" for num in range[1, 5]] print[res]

Output: [‘No’, ‘No’, ‘Yes’, ‘No’]

Do comment if you have any doubts and suggestions on this Python List tutorial.

Note: IDE: PyCharm 2021.3 [Community Edition]

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

Given a list comprehension you can append one or more if conditions to filter values.

[ for in if ]

For each in ; if evaluates to True, add [usually a function of ] to the returned list.

For example, this can be used to extract only even numbers from a sequence of integers:

[x for x in range[10] if x % 2 == 0] # Out: [0, 2, 4, 6, 8]

Live demo

The above code is equivalent to:

even_numbers = [] for x in range[10]: if x % 2 == 0: even_numbers.append[x] print[even_numbers] # Out: [0, 2, 4, 6, 8]

Also, a conditional list comprehension of the form [e for x in y if c] [where e and c are expressions in terms of x] is equivalent to list[filter[lambda x: c, map[lambda x: e, y]]].

Despite providing the same result, pay attention to the fact that the former example is almost 2x faster than the latter one. For those who are curious, this is a nice explanation of the reason why.

Note that this is quite different from the ... if ... else ... conditional expression [sometimes known as a ternary expression] that you can use for the part of the list comprehension. Consider the following example:

[x if x % 2 == 0 else None for x in range[10]] # Out: [0, None, 2, None, 4, None, 6, None, 8, None]

Live demo

Here the conditional expression isn't a filter, but rather an operator determining the value to be used for the list items:

if else

This becomes more obvious if you combine it with other operators:

[2 * [x if x % 2 == 0 else -1] + 1 for x in range[10]] # Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]

Live demo

If you are using Python 2.7, xrange may be better than range for several reasons as described in the xrange documentation.

[2 * [x if x % 2 == 0 else -1] + 1 for x in xrange[10]] # Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]

The above code is equivalent to:

numbers = [] for x in range[10]: if x % 2 == 0: temp = x else: temp = -1 numbers.append[2 * temp + 1] print[numbers] # Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]

One can combine ternary expressions and if conditions. The ternary operator works on the filtered result:

[x if x > 2 else '*' for x in range[10] if x % 2 == 0] # Out: ['*', '*', 4, 6, 8]

The same couldn't have been achieved just by ternary operator only:

[x if [x > 2 and x % 2 == 0] else '*' for x in range[10]] # Out:['*', '*', '*', '*', 4, '*', 6, '*', 8, '*']

See also: Filters, which often provide a sufficient alternative to conditional list comprehensions.


PDF - Download Python Language for free

When using a list comprehension with an if, is it possible to have an else clause?

Answer

Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension. The if/else is placed in front of the for component of the list comprehension.

divbythree = [ "Yes" if number % 3 == 0 else "No" for number in range[1,20]] print[divbythree]

16 Likes

Hello,

My post is for the same exercise. I completed the list comprehension and I’m tinkering with the original for loop:

heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster2 = [] for i in heights: if i > int[161]: can_ride_coaster2 += i print[can_ride_coaster2]

I received a TypeError: ‘int’ object is not iterable, and I read some articles that wrote that for the ‘for loops’, only strings, list, tuples are iterable. Hope to get a second opinion on this because heights are a list, isn’t it?

5 Likes

dtsyi:

can_ride_coaster2 += i

We cannot add a number to a list of numbers using concatenation. In the present form we would need to append it.

However, we can concatenate a list to a list…

can_ride += [1]

Now the concatenation is of two iterables.

9 Likes

dtsyi:

heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster2 = for i in heights: if i > int[161]: can_ride_coaster2 += i print[can_ride_coaster2]

Ah, got it! I got confused when I thought the I couldn’t iterate through the list of heights because they were numbers.

for i in heights: if i > 161: can_ride_coaster2 += [i] print[can_ride_coaster2]

There we go! Thank you mtf!

2 Likes

Somehow this is not correct,

heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [heights for heights in heights if heights > int[161]] can_ride_coaster += heights print [can_ride_coaster]

Expected Result:

Expected can_ride_coaster to be printed.

what I got is:

[164, 170, 163, 163, 161, 164, 156, 144, 158, 170, 163, 163, 157]

Can someone help me?

arcpro99996:

for heights in heights

Same name cannot be used for both variables.

[height for height in heights if height > 161]

2 Likes

If you’ll notice, the first 4 elements of your result are the expected result. Your code will produce the expected result if you remove the following line:

arcpro99996:

can_ride_coaster += heights

This line is concatenating the original heights list to your can_ride_coaster list. While using the same name as the list for your variable in your for statement as @mtf pointed out is bad practice and confusing, it actually does work. Happy coding!

1 Like

I removed the line:

can_ride_coaster += heights

what i get now as an answer is:

[164, 170, 163, 163]

The answer is still not correct, even if the answer seems correct from my point of view. The system still expect can_ride_coaster to be printed, and not the actual numbers [164, 170, 163, 163].
I am a little bit confused on how i should solve this.

Could you post a link to the specific exercise? The answer you get now is a list containing the heights that meet the requirement to ride the coaster which seems to be the expected output. If you post a link to the exercise, I’ll try to help you sort this out.

Sorry for taking so long to get back to you. I just completed the exercise without issue. The correct output is: [164, 170, 163, 163]. I then reset the exercise, and ran your code. I received the same error that you described even though the output was correct. I then reset the exercise again, pasted your code in again, and it ran without error producing the correct output. I’m not sure what the issue is, but it appears to be some inconsistency with SCT for the exercise. Try resetting the exercise, and paste your code back in. If it doesn’t work, just click “Get Solution”, and move on knowing that your code does meet the requirement. One comment on your code. There is no need to use int[161]. The number 161 is already an integer, and your code will perform just as well without int[]. Happy coding!

1 Like

My solution

heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [can_ride_coaster for can_ride_coaster in heights if can_ride_coaster > 161]

While i understand the exercise [in the face value], i am yet to have a deep comprehension of why we have [word for word…], [[can_ride_coaster for can_ride_coaster…]. While i do not just want to cram that, i properly want to understand the principle behind it. May be i need a better interpretation. My question is, why does “word” or "can_ride_coaster " came first?

Hello, @sodiqolabodeafolayan.

In a list comprehension, the first [leftmost] value inside the square brackets is the value or placeholder that will populate the list. It isn’t necessarily always the same as the iterator variable in the for loop.
Consider these examples:

my_list = [1, 2, 3, 4, 5, 6, 7, 8] def say_hi[lst]: return ['Hi!' for n in lst if n < 5] print[say_hi[my_list]]

Output:

[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]

This one uses the iterator variable multiplied by 2 in the output:

my_list = [1, 2, 3, 4, 5, 6, 7, 8] def multiply_by_two[lst]: return [n * 2 for n in lst if n < 5] print[multiply_by_two[my_list]]

Output:

[2, 4, 6, 8]

2 Likes

sodiqolabodeafolayan:

can_ride_coaster = [can_ride_coaster for can_ride_coaster in heights if can_ride_coaster > 161]

The beauty of list comprehensions is that they are abstracts of an otherwise verbose task. Given that, it would follow that we don’t need verbosity in them.

@midlindner demonstrates that above by using a simple letter symbol in place of a verbose name.

can_ride_coaster = [x for x in heights if x > 161]

The variable name tells us what is being abstracted. That is sufficient information to permit not infusing the abstraction with all that clutter.

In the end, it helps to get to the bottom of the mechanics in play. Abstractions are generic, like functions. The verbosity needs to left where it has real meaning and not be allowed to pollute otherwise re-usable functions or one-off abstractions.

Witness…

def passes[h, d]: return h > d def can_ride[array, disallowed]: return [x for x in array if passes[x, disallowed]] >>> heights = [161, 164, 156, 144, 158, 170, 163, 130, 163, 157] >>> can_ride_coaster = can_ride[heights, 161] >>> can_ride_ferris_wheel = can_ride[heights, 135] >>> can_ride_coaster [164, 170, 163, 163] >>> can_ride_ferris_wheel [161, 164, 156, 144, 158, 170, 163, 163, 157] >>>

3 Likes

heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = [height for height in heights if height > 161]

print[can_ride_coaster]

thanks for this great example

Just saw this post so the reply is a bit late. Did you ever get the answer you were looking for? It seems to me your question is why wasn’t ‘can_ride_coaster’ printed. If that’s so it’s because the argument you were passing to the print function was the can_ride_coaster list and not the string ‘can_ride_coaster’.

Hi there,

Thank you for answering my question.

I have deleted my account on codeacademy several months ago.

You can consider the question obsolet.

Best regards

Hey, building upon this, can you please look at this code?

# Example 1 - if divbyfour = [x for x in range[1,20] if x % 4 == 0] print["These numbers are divisible by 4 " + str[divbyfour]] # Example 2 - if... else divbythree = [ "Yes" if number % 3 == 0 else "No" for number in range[1,20]] print["Numbers divisible by 3 " + str[divbythree]]

Ordering in the first example goes ‘for’ then ‘if’. If i reverse the ordering to ‘if’ then ‘for’ i get syntax error.

Ordering in the second example goes ‘if… else’ then ‘for’. If i reverse the order, i get syntax error.

Is there any logic behind why the ordering changes when using only if as opposed to when using ‘if… else’? Or is it just a Python syntax rule that i should mug up? Thanks in advance!

next page →

Video liên quan

Chủ Đề