List comprehension instead of extend in loop

Question:

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))
Asked By: Ashtart

||

Answers:

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])))
Answered By: John Doe

A set comprehension seems appropriate. Please also note that I’ve used // rather than / as floating point numbers are not relevant to this problem.

from math import sqrt

def divisors(n):
    return {x for div in range(1, int(sqrt(n)) + 1) 
              if not (n % div)
              for x in [div, n // div]}

divisors(15)
# {1, 3, 5, 15}

If you really wish to have a list, it’s easy enough to turn the set into a list.

list(divisors(15))
# [1, 3, 5, 15]
Answered By: Chris

refer the link:
list.extend and list comprehension

def divisors(n):
    return list({i for div in range(1, int((n)**0.5) + 1) for i in [div, n // div] if n % div == 0})

sample input:

print(divisors(30))

Output

[1, 2, 3, 5, 6, 10, 15, 30]
Answered By: AMISH GUPTA