-2

I have the following list:

In [572]: l2
Out[572]: [(), (), ()]

I need to check if all tuples within the list are empty.

My attempt:

In [581]: x = [True if i else False for i in l2]

In [584]: x
Out[584]: [False, False, False]

In [583]: not any(x)
Out[583]: True

I used a list comprehension to create a list with boolean values (True) if tuple is not empty, (False) if tuple is empty.

Then I'm using any to check if all elements is my list all False.

Is there a more concise way of doing all this?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
  • 4
    `not any(l2)`... – deceze Mar 26 '21 at 08:29
  • @deceze How does `not any(l2)` work? In my understanding `any` will take an iterable and return `False` if all elements in iterable are `False`. How is `()` evaluated to `False` automatically? – Mayank Porwal Mar 26 '21 at 08:33
  • 4
    It's *falsey*. The same way that `True if i else False` evaluates the value as truthy or falsey. – deceze Mar 26 '21 at 08:35
  • 1
    Tip: any variation of `True if ... else False` is basically always superfluous. The `...` itself is already truthy or falsey, otherwise the `if` wouldn't work at all. If you require to turn your arbitrary value into an actual boolean, use `bool(...)`. – deceze Mar 26 '21 at 08:41
  • If you actually need for some reason to get a `True` or `False` value explicitly, you can still do that more concisely: just use the `bool` built in (i.e, the type itself). – Karl Knechtel Mar 26 '21 at 08:43

1 Answers1

1

@deceze has already provided a way which is probably the best with not any(l2).

Here is another way using the generator expression:

l2 = [(), (), ()]
try:
    out = next(elt for elt in l2 if elt)
except StopIteration:
    print("all elements are empty")
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35