3

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?

2
  • 1
    all is just a function in Python, and it can be easily implemented with for. You might consider trying to write all yourself as a good programming exercise. Commented May 10, 2019 at 3:34
  • 3
    Just read the docs for all Commented May 10, 2019 at 3:35

2 Answers 2

4

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 :)

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.