Reputation: 1111
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?
Upvotes: 2
Views: 71
Reputation:
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.
Upvotes: 8
Reputation: 22964
The reason why you were getting wrong result was because you are already creating a new list using list comprehension by applying the desired condition, So if we do a little breakdown then:
>>> print [name for name in names if name[0] == "R"]
>>> ['Rhonda', 'Ryan', 'Red Rackham']
>>> print all(['Rhonda', 'Ryan', 'Red Rackham'])
>>> True
So the correct way may be:
names = ["Rhonda", "Ryan", "Red Rackham", "Paul"]
res = all(map(lambda x : x[0]=="R", names))
# map() returns: [True, True, True, False]
# all([True, True, True, False]) == False
print res
Upvotes: 0
Reputation: 99001
names = ["Rhonda", "Ryan", "Red Rackham", "Paul"]
if all(c[0] == "R" for c in names):
print "ALL MATCH"
Demo:
Upvotes: 0
Reputation: 4812
names = ["Rhonda", "Ryan", "Red Rackham", "Paul"]
print all(map(lambda name: name[0] == "R", names))
# prints False
names = ["Rhonda", "Ryan", "Red Rackham"]
print all(map(lambda name: name[0] == "R", names))
# prints True
Upvotes: 0