Dvb12
Dvb12

Reputation: 19

Lists containing number

I'm trying to write a loop that checks whether a certain number in lists in a list is not appearing. For example: if I have the list

[[1,'O', 3], [4, 5, 6], [7, 8, 'X']]

I want to write a loop that checks whether number 2 appears in one of the lists, and if not, asks you to pick a new number. So far I'm stuck on this:

move = 2
for i in range(3):
    for j in range(3):
        if move not in board[i][j]:
            move = int(input("Number already taken. Pick another"))

But it doesn't work. It seems to be a fairly straightforward check, but I don't know why it wouldn't run. Does anybody have a better suggestion how to check these lists for a given number?

Cheers

Upvotes: 2

Views: 105

Answers (4)

Yun Luo
Yun Luo

Reputation: 1686

try to use any function.

m = [[1,'O', 3], [4, 5, 6], [7, 8, 'X']]
while True:
    move = int(input('....'))
    if any(move in row for row in m):
        break

Upvotes: 6

kederrac
kederrac

Reputation: 17322

you could use a generator expression:

my_list = [[1,'O', 3], [4, 5, 6], [7, 8, 'X']]

move = 2
numbers = (e for l in my_list for e in l)

if move not in numbers:
    move = int(input("Number already taken. Pick another"))

a more compact version:

numbers = (e for l in my_list for e in l)
move = 2 if 2 in numbers else int(input("Number already taken. Pick another"))

Upvotes: 0

pastaleg
pastaleg

Reputation: 1838

While Andrea's answer is more concise and clean, the answer to why your code does not work is because you are comparing two variables with the not in comparator which expect a list on the right hand. More info on that here: https://docs.python.org/3/reference/expressions.html#membership-test-operations

So to solve it, either remove the inner loop and compare the move with the inner lists, or use an equality comparator instead. Both options are below:

board = [[1,'O', 3], [4, 5, 6], [7, 8, 'X']]

move = 2
for i in range(3):
  if move not in board[i]:
    move = int(input("1: Number already taken. Pick another"))

for i in range(3):
    for j in range(3):
        if move == board[i][j]:
            move = int(input("2: Number already taken. Pick another"))

Upvotes: 0

Andrea
Andrea

Reputation: 4503

Given your environment:

target = 2
list_of_lists = [[1,'O', 3], [4, 5, 6], [7, 8, 'X']]

I would do something like that with a one-liner:

True in [target in element for element in list_of_lists]

Upvotes: 0

Related Questions