You're not asking if the list itself is true here, you're asking if every member of the list is true. And they are: every single one of those 0 items is true - not a single one was false! More generally, this comes down to what is called a " vacuous truth " regarding universal statements. Ie. is the statement: "All unicorns in my house are white" true? In formal logic, the answer to this is "True". "All X are Y" is considered to be equivalent to "There is no X that is non-Y". There are no unicorns in my house that are not white (because there are no unicorns in my house), so this is obviously true, which likewise gives us the answer to the equivalent "All the unicorns in my house are white" statement (And likewise "All unicorns in my house are purple" is also true). In English, this might seem a bit confusing, because we're often not making statements about empty sets - conversationally, the fact that we talk about something tends to hint at or imply that it exists. But in logic, it's often necessary to talk about empty (or potentially empty) sets, and this is a consistent way to treat them. Answer from Brian on reddit.com
🌐
W3Schools
w3schools.com › python › python_booleans.asp
Python Booleans
The bool() function allows you ... is True, except empty strings. Any number is True, except 0. Any list, tuple, set, and dictionary are True, except empty ones....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-test-if-a-list-is-completely-true
Test if a list is Completely True - GeeksforGeeks
July 12, 2025 - For example, a = [True, True, True] we need to find that whole list is True so that output should be True in this case. all() function in Python returns True if all elements in an iterable are truthy otherwise it returns False.
Top answer
1 of 3
13
  • You can just use x[n_trues:] rather than x[n_trues:len(x)].
  • Your comments don't really say more than the code. And so I'd recommend removing the comments.
  • If you want to keep your code documented use docstrings, which can be exported to your documentation via tools like Sphinx.
  • As commented by Konrad Rudolph, you can remove the and not any(should_be_false) as this will always fail if the all fails.
def check_true_then_false(x):
    """Check first n values are True and the rest are False."""
    return all(x[:sum(x)])

If you want your code to work with iterators, not just sequences then you can instead use:

def check_true_then_false(it):
    """Check first n values are True and the rest are False."""
    it = iter(it)
    # Takes advantage of the iterating side effect, where it consumes the iterator.
    # This allows `all` to simultaneously checks `it` starts with trues and advances `it`.
    return all(it) or not any(it)

For the following two inputs all will result in:

>>> all([True] * n)
True
>>> all([True] * n + [False, ...])
False

However it will mean that it is still [...] as all and any are lazy. Meaning that we just need to check the rest are false. Meaning all slices the iterator for you without you having to. Leaving any with:

>>> any([False] * n)
False
>>> any([False] * n + [True, ...])
True
2 of 3
8

Basically, you want your list of booleans to be sorted.

Specifically, since True > False, you want your list to be sorted in decreasing order:

def check_true_then_false(booleans):
    return booleans == sorted(booleans, reverse=True)

Done!

>>> test_cases = [[True],
...               [False],
...               [True, False],
...               [True, False, False],
...               [True, True, True, False],
...               [False, True],
...               [True, False, True]]
>>> 
>>> print([check_true_then_false(test_case) for test_case in test_cases])
[True, True, True, True, True, False, False]
🌐
GeeksforGeeks
geeksforgeeks.org › python-test-for-false-list
Python | Test for False list - GeeksforGeeks
April 17, 2023 - Define a function is_list_false that takes a list test_list as an argument. If the length of the list is 0, return True, since an empty list is considered completely false.
Find elsewhere
Top answer
1 of 2
27

Because:

>>> True == 1
True
>>> False == 0
True

Boolean is a subclass of int. It is safe* to say that True == 1 and False == 0. Thus, your code is identical to:

>>> [1, 2][1]
2
>>> [1, 2][0]
1
>>> [1, 2, 3][1]
2

That's why when you add more elements, the output will remain the same. It has nothing to do with the length of the list, because it is just basic indexing affecting only the first two values.


*: NB: True and False can actually be overritten in Python <=2.7. Observe:

>>> True = 4
>>> False = 5
>>> print True
4
>>> print False
5

*: However, since Python 3, True and False are now keywords. Trying to reproduce the code above will return:

>>> True = 4
  File "<stdin>", line 1
SyntaxError: assignment to keyword
2 of 2
12

What's happening here is a little confusing, since [1,2,3][True] has two sets of []s that are being interpreted in different ways.

What's going on is a little more clear if we split the code over a few lines.

The first set of []s construct a list object. Let's assign that object the name a:

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

The second set of [] specify an index inside that list. You'd usually see code like this:

>>> a[0]
1
>>> a[1]
2
>>>

But it's just as valid to use the list object directly, without ever giving it a name:

>>> [1,2,3][0]
1
>>> [1,2,3][1]
2

Lastly, the fact that True and False are useable as indexes is because they're treated as integers. From the data model docs:

There are three types of integers:

Plain integers....

Long integers.....

Booleans

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

Thus, [1,2,3][True] is equivalent to [1,2,3][1]

🌐
Mimo
mimo.org › glossary › python › value-false
False Values in Python: Unveiling True and False
The None object, which denotes the absence of a value or a null value in Python · Falsy values allow for concise and expressive conditional checks. Instead of checking if a list is empty by comparing its length to 0, you can also use the list itself: ... my_list = [] if not my_list: # This evaluates to True because an empty list is falsy print("The list is empty.")
🌐
Python.org
discuss.python.org › ideas
Add basic boolean indexing to list - Ideas - Discussions on Python.org
April 18, 2022 - Many Python libraries related to data science support concept of boolean indexing (Indexing on ndarrays — NumPy v2.3 Manual). I would like to propose limited version of this concept that could be useful to regular Python…
🌐
Reddit
reddit.com › r/learnpython › how to remove boolean true/false from a list?
r/learnpython on Reddit: How to remove boolean True/False from a list?
February 24, 2023 -

I have a list that has floats, ints or boolean values. Example: [1.0, 27.8, 0, 23, 0.0, False, True]

How can I remove the boolean and leave the other numbers in the list? Where am I going wrong and what can I learn from this?

>>> ll = [1.0, 27.8, 0, 23, 0.0, False, True]

>>> ll.remove(False)
>>> ll
[1.0, 27.8, 23, 0.0, False, True]  # removes the first 0 it finds

This also didn't work:

>>> ll_without_booleans = [x for x in ll if isinstance(x, (float, int))]
>>> ll_without_booleans
[1.0, 27.8, 0, 23, 0.0, False, True]
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-boolean-list-initialization
Boolean list initialization - Python - GeeksforGeeks
July 11, 2025 - Let's explore some more ways and see how we can initialize a boolean list in Python. ... List comprehension allows us to initialize a boolean list based on a condition. This can be helpful when we need to create a boolean list where each element is determined by some logic. ... # Initialize a boolean list of size 5 where the condition is even index -> True a = [True if i % 2 == 0 else False for i in range(5)] print(a)
🌐
Team Treehouse
teamtreehouse.com › community › returning-true-or-false-instead-of-the-list
Returning True or False instead of the list (Example) | Treehouse Community
July 12, 2017 - Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [num % 2 == 0 for num in a] print(b) why does this only return "True" or "False" but not the numbers themselves?
🌐
Real Python
realpython.com › python-boolean
Python Booleans: Use Truth Values in Your Code – Real Python
June 16, 2023 - The Python Boolean type has only two possible values: ... No other value will have bool as its type. You can check the type of True and False with the built-in type():
Top answer
1 of 7
287

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

Timing comparisons(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

Don't use filter as a variable name, it is a built-in function.

2 of 7
78

Like so:

filtered_list = [i for (i, v) in zip(list_a, filter) if v]

Using zip is the pythonic way to iterate over multiple sequences in parallel, without needing any indexing. This assumes both sequences have the same length (zip stops after the shortest runs out). Using itertools for such a simple case is a bit overkill ...

One thing you do in your example you should really stop doing is comparing things to True, this is usually not necessary. Instead of if filter[idx]==True: ..., you can simply write if filter[idx]: ....

🌐
Python.org
discuss.python.org › python help
Random result from creating a comprehension Set out of a List - Python Help - Discussions on Python.org
January 1, 2024 - I am trying to learn the difference between List and Set, so I created an example using set comprehension to create a Set Z from a list MyList. The set Z will contain boolean values (True/False) based on whether each number in MyList is even or not. The first example is using set comprehension.
Top answer
1 of 4
28

Just use:

bool(my_list)

Which evaluates it as Python "truthiness" and returns a real Boolean.

2 of 4
5

99.9% of the time, performance doesn't matter, so just use bool(my_list) as Keith suggests.

In the cases where performance does matter though, the nature of bool means it's actually quite slow, at least on the CPython reference interpreter. It has to go through generalized function call paths, to generalized constructor paths, to generalized argument parsing for 0-1 arguments (and in all but the most recent versions of Python, checking for keyword arguments), all to eventually just increment as reference count on a singleton and return it.

You can see how much this costs with ipython microbenchmarks (on my Windows x64 3.6.3 build):

In [1]: %%timeit -r5 l = []
   ...: bool(l)
   ...:
118 ns ± 0.808 ns per loop (mean ± std. dev. of 5 runs, 10000000 loops each)
In [11]: %%timeit -r5 l = [1]
    ...: bool(l)
    ...:
117 ns ± 0.306 ns per loop (mean ± std. dev. of 5 runs, 10000000 loops each)

It may not be obvious, but even on my relatively weak laptop, 117-118 nanoseconds just to determine truthiness is a bit much. Luckily, there are a couple other options. One is to abuse syntax to go through a dedicated path for truthiness evaluation (from here on out, I'll just test the empty list, the timings are basically identical either way):

In [3]: %%timeit -r5 l = []
   ...: not not l
   ...:
25 ns ± 0.289 ns per loop (mean ± std. dev. of 5 runs, 10000000 loops each)

That's a vast improvement; it takes roughly one fifth the time. On Python 3, using True if l else False also works with equal speed, but it's much slower than not not on Python 2, where True and False aren't protected literals, just built-in names that must be loaded dynamically each time.

Still, it's not perfect; sometimes you need a callable, e.g. to convert a lot of values to bool via a callback function (e.g. with map). Luckily, the operator module has you covered with operator.truth; while it's still a callable with all the overhead that entails, it's not a constructor, it takes exactly one argument (not 0-1), and it doesn't allow keyword arguments, all of which cost a surprising amount on the CPython reference interpreter. So when you can't use implicit truthiness testing or syntax based conversion with not not, and you still need the speed, operator.truth has you covered:

In [4]: from operator import truth

In [5]: %%timeit -r5 l = []
   ...: truth(l)
   ...:
52.1 ns ± 1.1 ns per loop (mean ± std. dev. of 5 runs, 10000000 loops each)

Twice as long as not not, but if you're using it with built-ins that call it repeatedly (like map) being able to push all the work to the C layer, avoiding byte code execution entirely, can still make it a win, and it's still well under half as costly as bool() itself.

Reiterating my earlier point though: 99.9% of the time, performance doesn't matter, so just use bool(my_list) as Keith suggests. I only mention this because I once had a scenario where that boolean conversion really was the hottest point in my code (verified through profiling), and using implicit truthiness testing (not even converting, just returning the list with the caller doing if myfunc():) shaved 30% off the runtime, and returning not not of the list still got nearly a 20% savings.