Python: What's the "Pythonic" way to process two lists?

list, list-comprehension, python

Solution

To convert two nested loops into a nested comprehension, you just do this:

[<expression> for x in list1 for y in list2]

If you've never thought through how list comprehensions work, the tutorial explains it:

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

In other words, the clauses from left to right in a comprehension match up with statements from top/outside to bottom/inside, and that's all there is to it.

This blog post attempts to put the same idea in yet another way, in case you haven't got it yet.

But here, you don't have an expression, you have a statement.

But you have an expression in there, the `y in x` part of the statement, and what you want to do is return True if it's every true for any value, which is exactly what `any` does. So:

return any([y in x for x in list1 for y in list2])

And really, you don't want to build the list here, just iterate over the values, so drop the square brackets to make it a generator expression instead:

return any(y in x for x in list1 for y in list2)

For the simple case of just iterating the cartesian products of multiple iterables, you may want to use `itertools.product` instead. In this case, I don't think it makes things any simpler or more readable, but if you had four lists instead of two—or an unpredictable-in-advance number of them—that might be a different story:

return any(y in x for x, y in product(list1, list2))

Problem

Say I have this code in Python. I'm a Perl programmer, as you may be able to tell. ``` # Both list1 and list2 are a list of strings for x in list1: for y in list2: if y in x: return True return False ``` What's a more Pythonic way to handle this? I assume a list comprehension could do it well, but I can't get my head around the "process two separate lists" part of this.

Original source