0

I want to check if all the 2nd values of a list's sub-lists are OK.

ls = [['a', None], ['b', None], ['c', 2]]

How can I check that ls does not have all None's in the 2nd index of its sub-lists without for loop?

Would something like filter(lambda sublist, idx=1, value=None: sublist[idx] == value, ls) do the trick?

Ma0
  • 15,057
  • 4
  • 35
  • 65
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 2
    "does not have all None's" means you want at least one value to be non-None? Use [`any()`](https://docs.python.org/3/library/functions.html#any)… – deceze Aug 28 '19 at 07:37

2 Answers2

3

any will look for the first entry for which the condition is True (and therefore not necessarily iterate over your whole list):

any(y is not None for x_, y in ls)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

Try with the all (or any) keyword and list comprehension syntax:

ls = [['a', None], ['b', None], ['c', 2]]

all_none = all(l[1] is None for l in ls)
one_not_none = any(l[1] is not None for l in ls)

print(all_none)  # >> False
olinox14
  • 6,177
  • 2
  • 22
  • 39
  • 1
    just fyi, this is not a list comprehension. It's a *generator expression*. – Ma0 Aug 28 '19 at 07:53
  • Yeah, of course, but syntax is the same and I had this link for documentation on list comprehensions so... But you're right. – olinox14 Aug 28 '19 at 08:02