Reputation: 531
I am learning python with a book: The exercise is to make a program that print True if all numbers in a list all odds.
I get it whit this approach
if all(x % 2 == 1 for x in list):
But the 'if all' approach is not yet explained. They only use while, if,for and booleans in the examples. Furthermore, seems to be a reflexive exercise about it is possible to do it, maybe not. It is possible to do it using the basic tools of above?
Upvotes: 3
Views: 71
Reputation: 41686
Yes, it is possible.
The Python code you wrote is very idiomatic, keep up that good work.
To see how to do it differently, you can look at programming languages that are less advanced, such as C. That is a very basic programming language which lacks the features for this if all
statement. Searching for "c all elements array true" should give you the code you are looking for. For such a simple piece of code, it's easy to translate the code back into Python.
Upvotes: 4
Reputation: 20500
If you look at the docs: https://docs.python.org/3/library/functions.html#all
all(iterable) .
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
So if all(x % 2 == 1 for x in li):
roughly translates to
def are_all_odds(num_list):
#Flag to keep track if we encounter an even number
flag = True
for num in num_list:
#Once we encounter a even number, we break the for loop
if num % 2 != 1:
flag = False
break
#Return the flag
return flag
We can test this function by doing
print(are_all_odds([1, 2, 3, 4]))
#False
print(are_all_odds([1, 3, 5]))
#True
Also just a suggestion, list
is a python builtin keyword, so don't use it in variables :)
Upvotes: 4