0

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

1 Answer 1

1
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]))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.