Skip to content Skip to sidebar Skip to footer

Not Comprehending List Comprehension In Python

While doing some list comprehension exercises, i accidentally did the code below. This ended up printing True/False for all 16 entries on the list. threes_and_fives =[x % 3 == 0 or

Solution 1:

What you may be missing is that there is nothing special about relational operators in Python, they are expressions like any others, ones that happen to produce Boolean values. To take some examples:

>>> 1 + 1 == 2True>>> 2 + 2 == 5False>>> [1 + 1 == 2, 2 + 2 == 5]
[True, False]

A list comprehension simply collects expressions involving elements of an iterable sequence into a list:

>>>[x for x in xrange(5)]      # numbers 0 through 4
[0, 1, 2, 3, 4]
>>>[x**2for x in xrange(5)]   # squares of 0 through 4
[0, 1, 4, 9, 16]

Your first expression worked just like that, but with the expression producing Booleans: it told Python to assemble a list of Boolean values corresponding to whether the matching ordinal is divisible by 3 or 5.

What you actually wanted was a list of numbers, filtered by the specified condition. Python list comprehensions support this via an optional if clause, which takes an expression and restricts the resulting list to those items for which the Boolean expression returns a true value. That is why your second expression works correctly.

Solution 2:

In the following code:

[x % 3 == 0 or x % 5 == 0 for x in range(16)]

The list comprehension is returning the result of x % 3 == 0 or x % 5 == 0 for every value in range(16), which is a boolean value. For instance, if you set x equal to 0, you can see what is happening at every iteration of the loop:

x = 0
x % 3 == 0 or x % 5 == 0
# True

Hope this helps, and happy FizzBuzzing

Solution 3:

In your first code sample, you are putting the value of

x % 3 == 0 or x % 5 == 0

into your list. As that expression is evaluated as true or false, you will end up with boolean values in the list.

In the second example, your condition is the condition for including x in the list, so you get the list of numbers which are divisible by 3 or 5. So, the list comprehension statement has to be read as

Include value x from the set {0,1,...,15} where condition (x is divisible by 3 or 5) is met.

EDIT: Fixed the set according to @user4815162342's comment.

Solution 4:

The following line is a condition returning True or False:

x % 3 == 0 or x % 5 == 0

So in your first attempt you have put it in your list

Solution 5:

This is simply the allowed expression syntax in Python. For a list comprehension, you need ...

  1. Item to appear in the final list
  2. Source of items
  3. Restrictions

The first example you gave evaluates to a Boolean value (True / False). The second one says to put the value of x into the list, with the restriction of divisibility.

Post a Comment for "Not Comprehending List Comprehension In Python"