What are the parts of list comprehension?


#1

Question

What are the parts of list comprehension?

Answer

List comprehension can be intimidating at first! So let’s break it down into its three basic parts:

  1. The part we want to calculate: [x … …]
  2. The range of values we want to operate in: [... for x in range(start, end) …]
  3. The condition, if any, that must be met: [... … if x == some_condition]
    This is the example given: doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0]
    The part being calculated is x * 2.
    The range to operate in is for x in range(1, 6).
    The condition that each x must meet to be used is if (x * 2) % 3 == 0.

FAQ: Learn Python - Advanced Topics in Python - List Comprehension Syntax
#2

List comprehensions can use nested loops which when combined with a test function can be very powerful. The following example uses a function to test if the product of two numbers is a palindrome.

Eg.

11 * 11 == 121

111 * 111 == 12321

Here is our test function…

def is_palindrome_product(a, b):
    return str(a * b) == str(a * b)[::-1]

The following looks at only 3 digit numbers…

r = range(100, 1000)
p = [(m, n, m * n) for m in r for n in r if is_palindrome_product(m, n)]
print (len(p))    # 2470
print (p[-1])     # (995, 583, 580085)

#3

You my friend are way ahead of me. :slight_smile:


#4

What is the syntax of list comprehension? Does the order matter?

Eg:
even_squares =[x ** 2 for x in range(1,11) if x % 2 == 0]
Could I type those same operations in a different order and have it create the identical list?


#5

list comprehension

    [(assignment expression) (for loop) (conditional)]

As we can deduce from this the order does matter.

x ** 2                  =>  assignment expression

for x in range(1, 11)   =>  for loop

if x % 2 == 0           =>  conditional

#6

Got it. Thanks mtf :smile:


#7

what about the example code as below,if…else With List Comprehension?
the for loop clause goes after the conditional clause?

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]

Also , when i rearranged the order of the code above like this (shown as below ),moving conditional clause to the middle position ,then it failed when i run it .

obj = ["Even"for i in range(10) if i%2==0 else "Odd"]
SyntaxError: invalid syntax

#8
>>> ['float' for x in range(10) if x % 1 else 'int']    # else is highlighted
SyntaxError: invalid syntax
>>> 

else must be before for else it might be construed as an else on the for and not the if.

>>> ['float' if x % 1 else 'int' for x in range(10)]
['int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int']
>>> ['float' if (x + x % 2 / 10) % 1 else 'int' for x in range(10)]
['int', 'float', 'int', 'float', 'int', 'float', 'int', 'float', 'int', 'float']
>>>