maharshi maharshi - 3 months ago 27
Python Question

How to remove outer list?

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.

And i am solving it like this:

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]]


I want the output to be
[1, 2, 4]


I can achieve this by:

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]


But is there a better way of achieving this ?

Answer

You don't need append, just use:

divisor_list = [i for i in list_range if n% i == 0]

This way you just assign the result of list comprehension, giving you one clean list. No need to append a list, that will nest a list in a list, and no need to initialize as an empty list. That's redundant because you add to the list just the next line. Just assign to list comprehension. As @joel goldstick mentioned, you can just loop over half of list_range because nothing will be a division if it's more than 1/2 the number:

list_range = list(range(1, n / 2))