Is there any evaluation of the expression in slim syntax for a list / tuple inside Python?

with numpy arrays, you can use some kind of inequality in the square bracket cut syntax:

>>>arr = numpy.array([1,2,3]) >>>arr[arr>=2] array([2, 3]) 

Is there any equivalent syntax in python regular data structures? I expected to get an error when I tried:

 >>>lis = [1,2,3] >>>lis[lis > 2] 2 

but instead of excluding some type, I get a return value of 2, which does not make much sense.

ps I could not find documentation for this syntax at all, so if someone could point me to numpy for it and for regular python (if it exists), that would be great.

+4
source share
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 these two types, so it compares class names in alphabetical order ( "list" > "int" ). Since True same as 1 , you get the item at index 1.

In Python 3.x, this expression will give you an error (a much less unexpected result).

  TypeError: unorderable types: list ()> int ()

To do what you want, you must use list comprehension:

 [x for x in lis if x > 2] 
+7
source

Use list:

 [a for a in lis if a>=2] 
+1
source

Source: https://habr.com/ru/post/1382068/


All Articles