-4

I have this code:

x = ["Hello", "World"]
y = ["Hi", "Guys"]
z = [x, y]

The following line will return False:

"Hello" in z

But I need a way to make it return yes. I need a way to control if an object is in one of the lists contained in z. The only way is a for loop?

1 Answers1

2

You do need some kind of loop, yes, because "Hello" is indeed not in z -- it is in x which is in z:

>>> x = ["Hello", "World"]
>>> y = ["Hi", "Guys"]
>>> z = [x, y]
>>> "Hello" in x
True
>>> x in z
True
>>> any("Hello" in a for a in z)
True

In the expression above, a iterates over x and y, and we check to see if any of those values of a satisfies "Hello" in a.

Here's a similar-but-different approach which flattens z (using nested for loops) before using in:

>>> [b for a in z for b in a]
['Hello', 'World', 'Hi', 'Guys']
>>> "Hello" in (b for a in z for b in a)
True

As before, a iterates over each list in z, and now within that iteration we have b iterate over each string in each a, which produces a single iterable that contains all four strings; we can then use "Hello" in (that iterable) and get the desired result.

Samwise
  • 68,105
  • 3
  • 30
  • 44