1
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.

1
  • 3
    Because the list comprehesion returns [1, 3, 4, 5] all the elements in this list evaluates to True Commented Jan 11, 2017 at 11:52

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

shouldn't zip(x, x[1::]) be faster ? (no need to generate an extra copy of the first list). And you removed the [] without explaining why it was useless.
3

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.

5 Comments

It's True because the list is not empty, regardless of the sign of the numbers inside it.
@MarounMaroun Wrong!. A list containing 0 (or something falsy) will not return True with all
@MosesKoledoye Try if [0]: print True
@MarounMaroun Try if all([0]): print True
My mistake, changing my vote. Thanks for the correction everyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.