How to remove outer list?
<p>I have a simple example,
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p>

<p>And i am solving it like this:</p>

<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
divisor_list.append([i for i in list_range if n%i==0])
print divisor_list
#output:
#[[1, 2, 4]]
</code></pre>

<p>I want the output to be <code>[1, 2, 4]</code></p>

<p>I can achieve this by:</p>

<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
for i in list_range:
    if n % i == 0:
        divisor_list.append(i)
print divisor_list
#output:
#[1, 2, 4]
</code></pre>

<p>But is there a better way of achieving this ?</p>

<p>It makes no sense to loop through all range of numbers, it's a waste! Just try to prove there are no more divisors after n/2, here's another benchmarked version comparing an alternative method <code>f2</code>:</p>

<pre><code>import math
import timeit


def f1(num):
    return [i for i in range(1, num + 1) if num % i == 0]


def f2(num):
    square_root = int(math.sqrt(num)) + 1
    output = []
    for i in range(1, square_root):
        if (num % i == 0 and i * i != num):
            output.append(i)
            output.append(num / i)
        if (num % i == 0 and i * i == num):
            output.append(i)

    return output


def bench(f, N):
    for n in range(1, N):
        f(N)

N = 10000
print timeit.timeit('bench(f1, N)', setup='from __main__ import bench, f1, N', number=1)
print timeit.timeit('bench(f2, N)', setup='from __main__ import bench, f2, N', number=1)
</code></pre>

<p>Results on my cpu are:</p>

<pre><code>4.39642974016
0.124005777533
</code></pre>

<p>f2 won't give a sorted list, but that's irrelevant, you didn't mention that in your question</p>

python list python-2.7