Function that creates list inside list

Asked

Viewed 83 times

1

def add_divisors(list_num):
    final_list = []
    divisors = []
    for number in list_num:
        for x in range(1, number+1):
            if number % x == 0:
                divisors.append(x)
                final_list.extend(divisors.copy())
                divisors.clear()
    return final_list
        
    
print(add_divisors([3, 4, 6]))

Basically this program prints:

[1, 3, 1, 2, 4, 1, 2, 3, 6]

I would like to put the divisors of each number within a separate list for each, example:

[[1, 3], [1, 2, 4], [1, 2, 3, 6]]

2 answers

4


Internally you need to create the internal lists, so at each step you create a different list, so initialize the empty list and at the end of the internal loop add that list to the external list. It’s very simple, the internal list should behave the same, there’s no reason to do it differently. The only difference is that on the internet should add something only conditionally, but the rest the structure is identical, ie to do the same operation you perform the same operation.

The current code is confusing and does things that should not.

def add_divisors(list_num):
    final_list = []
    for number in list_num:
        divisors = []
        for x in range(1, number + 1):
            if number % x == 0:
                divisors.append(x)
        final_list.append(divisors)
    return final_list

print(add_divisors([3, 4, 6]))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

4

You can accomplish this task by using a list comprehension. The documentation thus defines:

List comprehensions provides a concise way to create a list. Common applications are to create new lists where each element is the result of some operation applied to each element of another sequence or iterable, or create a subsequence of elements that satisfy a certain condition.

And in this case it is possible to apply a list comprehension where each sublist element of the resultado will be formed only by the dividers of n which is a number contained in the entry list_num.

def add_divisors(list_num):
    resultado = []
    for n in list_num:
        resultado.append([x for x in range(1, n+1) if n % x == 0])
    return resultado

Example:

>>> print(add_divisors([3, 4, 6]))
[[1, 3], [1, 2, 4], [1, 2, 3, 6]]

It is still possible to achieve a more compact production by nesting list understandings:

def add_divisors2(list_num):
    return [[x for x in range(1, n+1) if n % x == 0] for n in list_num]

Example:

>>>print(add_divisors2([3, 6, 8]))
[[1, 3], [1, 2, 3, 6], [1, 2, 4, 8]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.