Is there any way to write a for loop in multiple lines in Python?

Viewed 169

I was going through a code which have the following function. I was wondering if it possible to write the for loops in multiple lines and return the same exact value as the following.

def RecordsLists(self, a, q):
   return set([a1.union(a2) for a1 in a for a2 in a if len(a1.union(a2)) == q])
2 Answers

Yes, you can use itertools.product(). Nested for loops are okay, but in my opinion they add an unnecessary amount of indentation.

from itertools import product
def RecordsLists(self, a, q):
    result = []
    for a1, a2 in product(a, repeat=2):
        union = a1.union(a2)
        if len(union) == q:
            result.append(union)
    return set(union)

Why not? All list comprehension are equal to loops.

def RecordsLists(self, terms, q):
    lst = []
    for term1 in terms:
        for term2 in terms:
            unioned = term1.union(term2)
            if len(unioned) == q:
                lst.append(unioned)
    return set(lst)

The only concern is the order of the two loops, but I think it won't affect result of this algorithm.

Related