pythonlist-comprehensionone-liner

List comprehension instead of extend in loop


Can I write this code in one line? I tried use chain in list comprehension.

def divisors(n):
    result = []
    for div in range(1, int(sqrt(n)) + 1):
        if n % div == 0:
            result.extend([div, n / div])
    return list(set(result))

Solution

  • Are you looking for something like this ?

    from math import sqrt
    import itertools
    
    def divisors(n):
        return list(set(itertools.chain.from_iterable([[div, n / div] for div in range(1, int(sqrt(n)) + 1) if n % div == 0])))