Reputation: 65
x = [0, 1, -2, 3, 4, 5]
all ([i for i in range (1, len(x)) if x [i-1] < x[i]]) ?
Why does this code print True
?
1 > -2 so it should print False
I think.
Upvotes: 1
Views: 78
Reputation: 500773
Your code doesn't do what you think it does. It first filters out some elements, and then evaluates a bunch of indices for truthiness. Since all of the indices are strictly positive, they are all truthy and your code always evaluates to True
.
From your description, what you're actually trying to do is this:
>>> all(x[i-1] < x[i] for i in range (1, len(x)))
False
This iterates over all pairs of consecutive elements and checks whether the first element is less than the second.
Another way to write this is:
>>> all(a < b for (a, b) in zip(x, x[1::]))
False
Upvotes: 5
Reputation: 31270
All values of i
come from range(1, len(x))
, so they're all positive integers. Positive integers are true-ish, so all()
will return True
.
Upvotes: 3