The T
The T

Reputation: 347

Confusion with Python's all(). Any solution that is easier to understand?

I've been finding a lot of semantic bugs in due because of confusion of swapping variables in the wrong spots for python's all()

The boolean expression I will share is intended to make sure that all elements in X exist in the new_list.

For example, if new_list = 1,2,3 and X = 1..to...9. The expression that I used returned TRUE when the answer is really FALSE.

>>> X = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> new_list = [1,2,3]
>>> all(elem in X for elem in new_list)
True
 # Notice that a False positive returned. Not all elements in X exist in new_list

Question

Since the boolean expression has caused semantic bugs in the past, is there any easier-to-read method? And perhaps an explanation for someone who is limited in coding?

Upvotes: -1

Views: 52

Answers (3)

Patrick Artner
Patrick Artner

Reputation: 51683

You read the syntax wrongly:

X = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = [1,2,3]
all(elem in X for elem in new_list)

This checks if all elem in new_list occure in X. What you probably wanted was

print( all( elem in new_list     for elem in X) )

            ^^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^   
           condition to check    what to check
           to get a True/False

meaning: check if all elem in X occure in new_list.


The documention of all() explaines it with a normal loop:

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

Upvotes: 2

Victor
Victor

Reputation: 2919

If you want to check if the elements in X are all in new_list, then you have to iterate for each element in X, then check if each of those elements is in new_list. You did the other way around:

X = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = [1,2,3]
all((number_in_x in new_list) for number_in_x in X)

That being said, using sets as @wim has provided is the better way of solving your problem.

Upvotes: 2

wim
wim

Reputation: 363243

An easier (and more efficient) way around may be to use set methods:

>>> set(X).issubset(new_list)
False

Upvotes: 3

Related Questions