I am trying to find the numbers smaller than the number(here i) towards the right of a list
If here 1,2,3,4 for any number there is no number towards its right which is smaller than that.I want to implement with any() and slicing.
But when I did that in python with the following code I am getting True but it should be False where am I missing the logic? and why is the output as True?
num=[1,2,3,4]
for i in range(1,len(num)-1):
print (any(num[i+1:])<num[i])
Output:
True
True
You need to check what's actually happening here. You have:
any(num[i+1:]) < num[i]
any
returns true if any of the elements of the list equivalent to true. Since all your numbers are non-zero, they are all equivalent to true. Then the right side compares to True
to num[i]
, so you have True < 2
and True < 3
. Since True
is equivalent to 1
these both result in 1.
You probably want something like:
print( any(x < num[i] for x in num[i+1:]))