9.4. Idiom Any
Return True if any element of the iterable is true.
If the iterable is empty, return False.
Built-in
9.4.1. Problem
>>> data = [True, False, True]
>>>
>>> result = False
>>> for x in data:
... if x is True:
... result = True
>>>
>>> result
True
9.4.2. Solution
>>> data = [True, False, True]
>>> result = any(data)
>>>
>>> result
True
9.4.3. Implementation
>>> def any(iterable):
... for element in iterable:
... if element:
... return True
... return False
9.4.4. Case Study 1
>>> USERS = [
... ('Alice', 'Apricot', 30),
... ('Bob', 'Banana', 31),
... ('Carol', 'Corn', 32),
... ('Dave', 'Durian', 33),
... ('Eve', 'Elderberry', 34),
... ('Mallory', 'Melon', 15),
... ]
Check if any user is younger than 18 years old:
>>> result = None
>>>
>>> for firstname,lastname,age in USERS:
... if age < 18:
... result = True
... break
... else:
... result = False
Check if any user is younger than 18 years old:
>>> result = any(age<18 for firstname,lastname,age in USERS)
9.4.5. Use Case - 1
>>> USERS = [
... {'username': 'alice', 'is_user': True, 'is_staff': True, 'is_admin': False},
... {'username': 'bob', 'is_user': True, 'is_staff': True, 'is_admin': False},
... {'username': 'carol', 'is_user': True, 'is_staff': False, 'is_admin': False},
... {'username': 'dave', 'is_user': True, 'is_staff': False, 'is_admin': False},
... {'username': 'eve', 'is_user': True, 'is_staff': True, 'is_admin': True},
... {'username': 'mallory', 'is_user': False, 'is_staff': False, 'is_admin': False},
... ]
>>>
>>>
>>> if any(user['is_admin'] for user in USERS):
... print('At least one person is an administrator')
... else:
... print('There are no administrators')
...
At least one person is an administrator
9.4.6. Assignments
# %% About
# - Name: Idiom Any IsAdmin
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Define `result: bool` with the result of checking
# if any user has admin role
# 2. User is admin if it's `uid` is less than 1000
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: bool` z wynikiem sprawdzenia
# czy którykolwiek użytkownik ma rolę admin
# 2. Użytkownik jest adminem, jeżeli jego `uid` jest mniejszy niż 1000
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is bool, \
'Variable `result` has invalid type, should be bool'
>>> result
True
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: bool
# %% Data
class User:
def __init__(self, username, uid):
self.username = username
self.uid = uid
def is_admin(self):
return self.uid < 1000
USERS = [
User('alice', uid=1000),
User('bob', uid=1001),
User('carol', uid=1002),
User('dave', uid=1003),
User('eve', uid=1003),
User('mallory', uid=1004),
User('root', uid=0),
]
# %% Result
result = ...
# %% About
# - Name: Idiom Any Impl
# - Difficulty: medium
# - Lines: 4
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Write own implementation of a built-in `any()` function
# 2. Define function `myany` with
# parameter `iterable: list[bool]`
# return `bool`
# 3. Don't validate arguments and assume, that user will
# always pass valid type of arguments
# 4. Do not use built-in function `any()`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `any()`
# 2. Zdefiniuj funkcję `myany` z parametrami:
# parametr `iterable: list[bool]`
# return `bool`
# 3. Nie waliduj argumentów i przyjmij, że użytkownik:
# zawsze poda argumenty poprawnych typów
# 4. Nie używaj wbudowanej funkcji `any()`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# myany([]) == False
# myany([True]) == True
# myany([False]) == False
# myany([True, False, True]) == True
# myany([True, True, True]) == True
# myany([False, False, False]) == False
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isfunction
>>> assert isfunction(myany)
>>> myany()
Traceback (most recent call last):
TypeError: myany() missing 1 required positional argument: 'iterable'
>>> myany([])
False
>>> myany([True])
True
>>> myany([False])
False
>>> myany([True, False, True])
True
>>> myany([True, True, True])
True
>>> myany([False, False, False])
False
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
from typing import Callable
myany: Callable[[list[bool]], bool]
# %% Data
# %% Result
def myany(iterable):
...