Skip to content

Check if any nested list within a 2d list both contains one value and does not contain another

I’m making a card game in python where the cards are stored in a 2D list, where the first layer of the list is each card and the second layer is the values a card has. I’m trying to make an if statement that checks if any card a player has in their hand (that is, any nested list within the list that is the player’s hand) contains a specific string in position 0 and does not contain an integer in position 5. The code is this:

if ("Melee" in [x[0] for x in p1_hand] and 0 not in [x[5] for x in p1_hand])

(followed by a bunch of ors for additional checks, which I know work properly and aren’t relevant)

I read on another Stack Overflow question that this is the most efficient way to check if an item exists within a 2D list, so I did it like this. However, it does not work for my purposes.

What I’m trying to do is check if there is any item in p1_hand where position 0 (p1_hand[x][0]) is “Melee” and position 5 (p1_hand[x][5]) is not 0 (what I’m actually checking for is if it’s 1 or higher, but using operators here returns an error). The results of the code I have at the moment are seemingly random, I can’t track down any pattern whatsoever as to when this if statement returns true or false.

I am totally at a loss as to how to get this to work, especially how to make a working solution which can fit into a single line in an if statement (which is important for what I’m trying to do).


You’re checking if there’s any card named Melee and any card where the value isn’t 0. But they’re not necessarily the same card.

Use the any() function to test both conditions on each card in the list.

if any(x[0] == "Melee" and x[5] != 0 for x in p1_hand):