How to append a list in another list while a for loop is running inside another for loop

I have been stuck on a really screwy problem. I want to append a list in another list while a for loop is running inside another for loop, It is sort of confusing for me but I tried in all ways. Even searched desperately on google with no solution.

Here is my attempt code:

def divisors(a):
  lst1=[]
  lst2=[]
  for x in a:
    for numbers in range(1,(x+1)):
      if x%numbers==0:
             
       lst1.append(numbers)
       lst2.append(lst1)
  return lst2
print(divisors([3,6,9]))

And here's the bizarre output:

[[1, 3, 1, 2, 3, 6, 1, 3, 9], [1, 3, 1, 2, 3, 6, 1, 3, 9], [1, 3, 1, 2, 3, 6, 1, 3, 9]]

As can be clearly seen, it append all the divisors of all the numbers again and again and arranges them in an unorganized manner What i expect is something like this:

[[1,3],[1,2,3,6],[1,3,9]]

Upvotes: 0

Views: 44

Answers (1)

Luuk
Luuk

Reputation: 14929

def divisors(a):
  lst2=[]
  for x in a:
    lst1=[]       # moved line
    for numbers in range(1,(x+1)):
      if x%numbers==0:
             
       lst1.append(numbers)
    lst2.append(lst1)    # two spaces removed
  return lst2

print(divisors([3,6,9]))

Upvotes: 1

Related Questions