Reputation: 131
I'm having difficulty using the all()
and any()
functions.
I have the following code below where I check for two adjacent digits are the same. Though the output of the print
statements is not what I expect.
From my understanding:
any
will return True
if any of the values are True
, while
the all
will only return True
if all of the values are True
Writing and running the code using Repl.it
test = 223456
number = str(test)
a = zip(number,number[1:])
#Checks for adjacent
equals = map(lambda x: x[0] == x[1], a)
print(list(equals)) #OUTPUT: [True, False, False, False, False]
print(any(equals)) #OUTPUT: False
print(all(equals)) #OUTPUT: True
Upvotes: 1
Views: 172
Reputation: 13888
As the other answer covered, the main reason is that your map
was already consumed prior to the any()
and all()
function. If you don't want to create a list
to store the data (e.g. if there's a large amount of data), you could do a parallel operation instead:
>>> print(any(equals), all(equals), sep='\n')
True
False
Or if you need to do something with those values:
>>> a, b = any(equals), all(equals)
>>> a
True
>>> b
False
Just to make it clear, both zip
and map
are both generators that get consumed once iterated.
Upvotes: 0
Reputation: 13106
You have already consumed equals
on the first call to list
, since map
is like a generator:
x = map(bool, range(1, 5))
print(list(x))
[True, True, True, True]
print(list(x))
[]
What you should do is convert it to a list
or some data structure that allows you to iterate over it twice:
equals = list(map(lambda x: x[0] == x[1], a))
print(any(equals)) # True
print(all(equals)) # False
Where all
will return True
on an empty collection:
all([])
True
Upvotes: 6