Rahat Zaman
Rahat Zaman

Reputation: 1382

List comprehension not working in python

Okay, so this code works fine for me.

a = [1, 2, 3, 4]
c = ['Three' if i is 3 else "Not Three" for i in a]
print(c)

Output:

['Not Three', 'Not Three', 'Three', 'Not Three']

But doing the same thing a bit more complexly, this code does not work. Where am I missing something?

import numpy as np

# 2 random np array of 10 elements ranging from -1 to 1
x = np.random.rand((10))*2 - 1
y = np.random.rand((10))*2 - 1

# xor = x>0 and y>0 or x<=0 and y<=0
xor = np.logical_or(
    np.logical_and(
        np.greater(x, 0), 
        np.greater(y, 0)), 
    np.logical_and(
        np.less_equal(x, 0), 
        np.less_equal(y, 0))
)
print(xor) # prints an array of random true and false of shape 200 

colors = np.array(['blue' if i is True else 'red' for i in xor])
# should print array of 'blue' and 'red' according to xor. But prints all 'red'
print(colors)

Outputs:

[ True  True False False  True  True  True False False  True]
['red' 'red' 'red' 'red' 'red' 'red' 'red' 'red' 'red' 'red']

Upvotes: 0

Views: 251

Answers (2)

Mike from PSG
Mike from PSG

Reputation: 5754

The problem is that your xor list is not a list of bool

Displaying the type of i in your loop provides this result:

print([type(i) if i == True else type(i) for i in xor])

[<class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>]

Anytime you use the keyword is the item must be exactly the item being compared against. There is exactly one value of True in the Python environment. An is comparison compares your variable against that one value of True.

In your case, the variable i is never actually True, it's a numpy bool with some value.
An == compare would work as each side of the == is evaluated and a bool to bool comparison is made in the end.

However, as previously stated, the preferred form has no comparison at all. if i is what you want.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49813

Don't use is:

colors = np.array(['blue' if i else 'red' for i in xor])

Upvotes: 3

Related Questions