Search code examples
pythonlistbug-trackinglist-comprehension

What's wrong in this python list comprehension?


I was just playing with list comprehensions and came across this :

h = [ b for b in range(1, 9) for k in range(b, b*10) if k%2==0 for j in range(2*k, k*k)]

Expected Result:

h = [1, 2, 3, 4, 5, 6, 7, 8]

Actual Result is not as expected, contains len(h) = 196000 items.

Please explain how this works ?


Solution

  • Why do you think this is the expected result?

    Your code is equivalent to:

    h = []
    for b in range(1, 9):
        for k in range(b, b*10):
            if k%2==0:
                for j in range(2*k, k*k):
                    h.append(b)
    

    So, for each number from 1 to 8, it will append it many times to the list

    You can also see how many times each number is added with the help of groupby:

    >>> for i,j in itertools.groupby(h):
        print(i, sum(1 for i in j))
    
    1 80
    2 960
    3 3640
    4 9120
    5 18392
    6 32472
    7 52328
    8 79008