Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there some kind of expression evaluation within list/tuple slicing syntax within Python?

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.

like image 881
inman320 Avatar asked Feb 23 '23 08:02

inman320


2 Answers

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]
like image 139
Mark Byers Avatar answered Mar 29 '23 23:03

Mark Byers


use list comprehension:

[a for a in lis if a>=2]
like image 23
Karoly Horvath Avatar answered Mar 29 '23 23:03

Karoly Horvath