FAQ: Learn Python: Loops - List Comprehensions

This community-built FAQ covers the “List Comprehensions” exercise from the lesson “Learn Python: Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise List Comprehensions

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

2 posts were split to a new topic: Why does this print every iteration?

15 posts were split to a new topic: How does indexing a string work? or What does word[0] in the example mean?

3 posts were split to a new topic: Can you break down the uses of the temporary variable word in the example?

3 posts were split to a new topic: Description problems in course material

2 posts were split to a new topic: Do I need to initiate an empty list before list comprehension?

Why are list comprehensions set up the way they are?

[EX]

list_comprehension = [“" + “for loop” + “if statement”]
what is the "
” part for?

[ expression | for parameter in loop | optional condition ]

We are building a list that will be composed of the expressions evaluated from the loop against the conditional.

evens = [x for x in range(1, 100) if x % 2 == 0]

odd_cubes = [x ** 3 for x in range(1, 22) if x % 2]

Both examples are trivial and can be simplified but study them, anyway.

     [x ** 3 for x in range(1, 22) if x % 2]
      ------ --------------------- --------
        /               |              \
expression           for loop       condition

Technically, a comprehension is itself an expression (anything that resolves to a value) so it contains no statements, only expressions. Note that all the expressions center around the parameter of the for loop.

2 Likes

is it possible to have nested loops with List Comprehensions? And if so how could that look like?

They are tricky to get one’s head around so if you are writing nested comprehensions, test your work thoroughly.

>>> bases = 2, 8, 10, 16
>>> exponents = 2, 3, 4, 5
>>> [b ** x for b in bases for x in exponents]
[4, 8, 16, 32, 64, 512, 4096, 32768, 100, 1000, 10000, 100000, 256, 4096, 65536, 1048576]
>>> 

What’s the advantage of list comprehensions? It seems a bit tacked on to this course.

Also, there’s an error with the answer which accepted this code, even though it’s not a list comprehension:

for a in heights:
  if a > 161:
    can_ride_coaster.append(a)

print(can_ride_coaster)

The above example is imperative code made of statements. It can not be written as a return statement or passed into a function or string literal (f-string).

A comprehension is an expression which can be written in a return statement, can be passed to a function, and can be printed.

>>> def range10():
    return [a for a in range(10)]    # return from a function

>>> print (f"{range10()}")
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def times2(s):
	return [x * 2 for x in s]

>>> print (f"{times2(range10())}")    # pass to a function
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> print (f"{[a for a in range(10)]}")    # print in an f-string
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

Expressions are a crucial part of functional programming. This concept will surface more and more.

1 Like

This might be a silly question, but does it matter where in the list comprehension we put the if/else statements?

In this first example, the if statement was placed at the end:

numbers = [2, -1, 79, 33, -45]
negative_doubled = [num * 2 for num in numbers if num < 0]
print(negative_doubled)

But in this other example, the if/else was placed in the middle:

numbers = [2, -1, 79, 33, -45]
doubled = [num * 2 if num < 0 else num * 3 for num in numbers ]
print(doubled)

Is there a preference as to where the if/else statements should go? Like if there is only an if statement, should it always be at the end and if there is an if/else statement, should it always be in the middle? Or does where we place an if statement or an if/else statement not really matter?

1 Like

When it is only if ... it can be on either side of the for ..., When it includes an else then it must be on the left.

2 Likes

Thank you!!
Is there a specific reason for this placement though? Or is that just how it is/how the syntax was set up?

An else on the right side will look like, for...else given there is no signature line or indentation.

1 Like

The if on the right hand side is part of the comprehension syntax, using it effectively filters out certain iterations from your loop

[5] == [x for x in range(10) if x == 5]  # True

The left hand side is an expression that is not specific to list comprehensions at all, it’s often called a ternary expression but the Python docs call it a conditional expression. You can write conditional expressions in most place as an expression is accepted, so far as I’m aware-

x = 5
"blue" == "red" if x > 10 else "blue"  # True

So whilst you can use it inside certain comprehensions it’s not limited to comprehensions and it does not have a filtering behaviour; it simply returns one of two expressions (like “red” or “blue” above).

A rather silly example (no filtering, just controls what expression evaluates to)-

example = [x if x != 5 else "bang" for x in range(10)]
print(example)
Out: [0, 1, 2, 3, 4, 'bang', 6, 7, 8, 9]
3 Likes

hey @mtf is it necessary to use list comprehension everytime in code cause i find easy writing loop without list comprehension. what are the benifits of using list comprehension?

Work with what is comfortable, and with what you know. Your workflow will expand over time. Some style guides actually recommend against expressions in favor of imperative constructs, for readability, but also for portability (as in port to another language).

One benefit of comprehensions is they are expressions that can be used as a return value, an argument, or within another expression, including string interpolation. We can even write a comprehension in a comprehension.

As expressions they are values, not constructs or statements. We cannot return a for or while loop, or write them inside an expression.

3 Likes

Meant to include an example…

def raised(bases, exponents):
    return [a ** x for a in bases for x in exponents]
>>> raised([2,3,4,5],[2,3,4,5])
[4, 8, 16, 32, 9, 27, 81, 243, 16, 64, 256, 1024, 25, 125, 625, 3125]
1 Like