Issue
I am attempting to use all()
but it is not working for me:
>>> names = ["Rhonda", "Ryan", "Red Rackham", "Paul"]
>>> all([name for name in names if name[0] == "R"])
True
>>>
I am trying to check if all the names begin with "R"
, and even though I added "Paul"
to names
, all()
still returns True
. How do I fix this so that all()
returns False
until "Paul"
is removed?
Solution
You misunderstand how all
works. From the docs:
all(iterable)
Return
True
if all elements of theiterable
are true (or if theiterable
is empty).
In your code, you are first collecting all names that start with R
into a list and then passing this list to all
. Doing this will always return True
because non-empty strings evaluate to True
.
Instead, you should write:
all(name[0] == "R" for name in names)
This will pass an iterable of booleans to all
. If all of them are True
, the function will return True
; otherwise, it will return False
.
As an added bonus, the result will now be computed lazily because we used a generator expression instead of a list comprehension. With the list comprehension, the code needed to test all strings before determining a result. The new code however will only check as many as necessary.
Answered By - user2555451
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.