Check if all or any item in a sequence satisfies a condition in Python

You can use the all() function to check if all the items in a sequence satisfy a certain condition.

Similarly, you can use the any() function to check if any of the items in a sequence satisfy a condition.

Here we iterate over a list of strings, for each item, we take its length with len().

The first line checks if all of the strings has length less than 4, which is False since only \’bmw\’ satisfies this condition.

The second line checks if any of the items satisfy the same condition of the string\’s length being less than 4, which is True since \’bmw\’ satisfies this condition.

car_brands = ['bmw', 'ferrari', 'mclaren']
all(len(car) < 4 for car in car_brands)
any(len(car) < 4 for car in car_brands)
False
True

Watch on Youtube

You can also watch this content on Youtube: