Kiko
Kiko

Reputation: 33

Is there any way I can make this small piece of code shorter? (Python)

first  = [0, 0, 0, 0]
second = [0, 0, 0, 0]
third  = [0, 0, 0, 0]
fourth = [0, 0, 0, 0]

while 0 in first and 0 in second and 0 in third and 0 in fourth:

The lists at the top begin with each value holding 0. As the program progress' I plan to change the values in the list from 0 to other numbers. Effectively, I want to know if there is way to re-write the 'while' statement to check if 0 is in any list, WITHOUT the long chain of 'while not in __ and not in __' etc. Cheers

Upvotes: 2

Views: 85

Answers (5)

Mike Robins
Mike Robins

Reputation: 1773

while 0 in first + second + third + fourth:
    # do stuff

Upvotes: 1

AGN Gazer
AGN Gazer

Reputation: 8378

while not any(map(all, [first, second, ...])):

Upvotes: 0

rafaelc
rafaelc

Reputation: 59274

You can also map

ls = [first, second, third, fourth]
func = lambda x: 0 in x

while all(map(func, ls)):
    #dostuff

Use all if you want 0 in first and 0 in second and .... Use any if you want 0 in first or 0 in second etc

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

while all(0 in i for i in [first,second,third,fourth]):
   ...

and If you want to check if any of the lists contain 0, do this:

while any(0 in i for i in [first,second,third,fourth]):
   ...

Upvotes: 2

dfundako
dfundako

Reputation: 8314

You can concatenate/combine all your lists and check truthyness:

while not all(first+second+third+fourth):

This checks for any False-y value and returns True if there is a 0.

Upvotes: 1

Related Questions