The Python Oracle

How to check all the elements in a list that has a specific requirement?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands

--

Chapters
00:00 How To Check All The Elements In A List That Has A Specific Requirement?
00:49 Accepted Answer Score 10
01:03 Answer 2 Score 5
01:10 Answer 3 Score 2
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/1672...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 10


Your description maps directly to the solution:

Edited for clarity:

mycards= ['0H','8H','7H','6H','AH','QS'] 
all((x == 'QS' or 'H' in x) for x in mycards)
#  True



ANSWER 2

Score 5


>>> mycards= ['0H','8H','7H','6H','AH','QS']
>>> all(x[-1] == 'H' or x == 'QS' for x in mycards)
True



ANSWER 3

Score 2


Since its your 'Homework' I'm not going to provide you with ready-made code. :)

Iterate over the list using a loop:

for eg.:

for el in mycards:

at each iteration you have to check either any of the two conditions are true or not.

if el == 'QS' or el[1] == 'H':

if card is either Queen of Spade or a Heart above condition will be true. Hope you get it till now. And if the condition is not true, simply return False.

If all the elements in your lists are checked by the loop and yet no False returned, hence the all cards are either Queen of Spade or a Heart. So return True after the loop ends.

Try on your own for a while, if still not getting I'll post the code at your request (but you'll have to show me what you tried :p)

Edit: Since you've tried it, I'm posting code too.

def HorQS(mycards):
    for i in mycards:
        if i != 'QS':
            if i[1] != 'H':
                return False
    return True

print HorQS(['0H','8H','7H','6H','AH','QS'])  # True
print HorQS(['0H','8H','7H','6H','AH','HS'])  # False
print HorQS(['0H','8H','7K','6H','AH','HS'])  # False