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 > 2returnsTrue. 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"). SinceTrueis the same as1, you get the item at index 1.In Python 3.x this expression would give you an error (a much less surprising result).
To do what you want you should use a list comprehension: