Gridzbi Spudvetch
Gridzbi Spudvetch

Reputation: 39

How do I check if a list of lists contains a value?

I'm trying to get my program to repeat an operation on a list of lists until there are no zeroes in the entire thing. I decided to go with seventy lists of ninety zeroes each (this is being used for a maze generator).

x=int(input("How many columns?\n"))
y=int(input("How many rows?\n"))
maze=[[0]*x for n in range(y)]

So with the inputs 90 and 70, there should be a total of 6300 zeroes. However, when I use

while 0 in maze[:]:
    #stuff

...the loop ends instantly without doing anything. I've also tried

while 0 in maze:
    #stuff

It's like Python completely ignores every single one of the six thousand three hundred zeroes in the maze list. I know of a way to fix this, but it involves slowly scrolling through the range of y values for every iteration. Is there a simpler way that allows it to look at all of the sublists in one line?

Upvotes: 1

Views: 6793

Answers (5)

blhsing
blhsing

Reputation: 106553

Checking if 0 exists in a 2-D matrix is always going to cost O(n*m), which is rather inefficient especially since your loop is going to iterate many times.

For your purpose I would suggest that you simply use a counter and increment it whenever your operation inside the loop sets an item of 0 to a non-0 value, so that you can use something like this as a condition for the while loop:

while counter < x * y:

Upvotes: 1

SAEERON
SAEERON

Reputation: 346

Numpy does not convert it to array if your sub-lists have different sizes

So, you'd better unravel your list:

x = [[0,0,0,1], [1,2,3,1,4,3,22,-4]]
x_flat = [val for sublist in x for val in sublist]
0 in x_flat 
>> True 

Upvotes: 0

John Gordon
John Gordon

Reputation: 33335

Use the any() function together with a generator expression:

while any(0 in sublist for sublist in maze):
    # do stuff

Upvotes: 7

blhsing
blhsing

Reputation: 106553

Since 0 is False in Boolean and all the items in maze are going to be numbers, you can use this instead:

while not all(map(all, maze)):

Upvotes: 0

rafaelc
rafaelc

Reputation: 59274

I think you could use numpy array to do what you want. The in operator will not find 0 in your list of lists, bu would work as intended with numpy.

Minimal and verifiable example:

x = [[0,0,0,1], [1,2,3,1]]
>>> 0 in x
False

np_x = np.array(x)
>>> 0 in np_x
True

Why 0 in x won't work?

Because x holds lots of objects of type list, and an object of type list will not be equal to 0 in any occasion. The in operator will not dig in to deepest level of your list to find out if there are zeroes there or not.

Upvotes: 5

Related Questions