Python - Values till False Element

Sometimes we need to process elements from a collection until we encounter a False element. Python provides several approaches: loops, itertools.takewhile(), list comprehension, and generators.

Using For Loop

The most straightforward approach is using a for loop with a break statement when a False element is found ?

def values_till_false(collection):
    result = []
    for element in collection:
        if not element:
            break
        result.append(element)
    return result

# Example usage
numbers = [2, 4, 6, 0, 8, 10]
result = values_till_false(numbers)
print(result)
[2, 4, 6]

Using itertools.takewhile()

The takewhile() function returns elements from an iterable as long as the predicate is True ?

from itertools import takewhile

def values_till_false(collection):
    return list(takewhile(bool, collection))

# Example usage
boolean_values = (True, True, True, False, True)
result = values_till_false(boolean_values)
print(result)
[True, True, True]

Using Generator Function

A generator function provides memory-efficient iteration by yielding elements one at a time ?

def values_till_false_gen(collection):
    for element in collection:
        if not element:
            return
        yield element

# Example usage
mixed_values = [True, 1, "hello", 0, "world"]
result = list(values_till_false_gen(mixed_values))
print(result)
[True, 1, 'hello']

Using While Loop with Iterator

Combine while loop with explicit iterator for more control over the iteration process ?

def values_till_false_while(collection):
    result = []
    iterator = iter(collection)
    
    while True:
        try:
            element = next(iterator)
            if not element:
                break
            result.append(element)
        except StopIteration:
            break
    return result

# Example usage
data = (1, 3, 5, 0, 7, 9)
result = values_till_false_while(data)
print(result)
[1, 3, 5]

Comparison

Method Memory Usage Readability Best For
For Loop Medium High Simple cases
takewhile() Low High Functional programming
Generator Very Low Medium Large datasets
While Loop Medium Low Complex iteration logic

Conclusion

Use itertools.takewhile() for clean, functional code. Use generators for memory efficiency with large datasets. Use for loops for simple, readable solutions in most cases.

Updated on: 2026-03-27T10:44:51+05:30

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements