Search code examples
pythonpython-3.xlist-comprehensionnested-loops

Convert nested for-loop to list comp and filter perfect squares from resultant list of dicts


I have written the following code:

a_list = []

for x in range(5):
    a_list.append(dict())
    for y in range(5):
        if (x != 0 and y != 0) and (x * x != x * y):
            a_list[-1][y] = x * y

The result is:

[{}, {2: 2, 3: 3, 4: 4}, {1: 2, 3: 6, 4: 8}, {1: 3, 2: 6, 4: 12}, {1: 4, 2: 8, 3: 12}]

But, I am having to get the same result using a list comprehension. How could I do this please?


Solution

  • You could write it, like so:

    a_list = [{y: x * y for y in range(5) if (x and y) and (x * x != x * y)}
              for x in range(5)]    
    
    # [{}, {2: 2, 3: 3, 4: 4}, {1: 2, 3: 6, 4: 8}, {1: 3, 2: 6, 4: 12}, {1: 4, 2: 8, 3: 12}]
    

    Sometimes a list comprehension is less readable or more complex than nested for loops, though.