Ayush
Ayush

Reputation: 33

Line comprehension in python

I want to write a small program that replaces certain values in an array with the desired value. The array (called "arr") contains about 10,000 elements of integer type and i would like to replace the digits 3,4 and 5 with 1.

I wrote the following code but it does not perform the desired function. Could someone help me figure out the logical error I am making. Thanks!

a=[1 if x==3|x==4|x==5 else x for x in arr]

Upvotes: 1

Views: 84

Answers (2)

user2357112
user2357112

Reputation: 280207

Logical OR is or, not |. | is bitwise OR. This list comprehension should be written as

a = [1 if x == 3 or x == 4 or x == 5 else x for x in arr]

or

a = [1 if x in (3, 4, 5) else x for x in arr]

Libraries like NumPy use | for broadcasted logical OR because or can't be overloaded, but even then, you generally need to parenthesize your comparisons to override the high precedence of |. If you're using NumPy, then instead of a list comprehension, you should do

a = np.where((arr == 3) | (arr == 4) | (arr == 5), 1, arr)

Upvotes: 1

UltraInstinct
UltraInstinct

Reputation: 44434

What you are doing now is called: bitwise OR. You should use a logical or: or.

Better yet, you can use in operator to test.

a = [1 if x in (3,4,5) else x for x in arr]

Upvotes: 3

Related Questions