with numpy arrays, you can use some kind of inequality within the square bracket slicing syntax:
>>>arr = numpy.array([1,2,3])
>>>arr[arr>=2]
array([2, 3])
is there some kind of equivalent syntax within regular python data structures? I expected to get an error when I tried:
>>>lis = [1,2,3]
>>>lis[lis > 2]
2
but instead of an exception of some type, I get a returned value of 2, which doesn't make a lot of sense.
p.s. I couldn't find the documentation for this syntax at all, so if someone could point me to it for numpy and for regular python(if it exists) that would be great.
In Python 2.x lis > 2
returns True
. This is because the operands have different types and there is no comparison operator defined for those two types, so it compares the class names in alphabetical order ("list" > "int"
). Since True
is the same as 1
, you get the item at index 1.
In Python 3.x this expression would give you an error (a much less surprising result).
TypeError: unorderable types: list() > int()
To do what you want you should use a list comprehension:
[x for x in lis if x > 2]
use list comprehension:
[a for a in lis if a>=2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With