Bronze
Bronze

Reputation: 11

Adding lists to lists with nested for loop

Is it possible to add lists to a list using a nested for loop? I've been trying to first create a separate list for the inner loop and then add it to a second list once it is completed, but this does not seem to work as it requires breaking the loop.

The below code yields a list with separate elements. I need to make it so that the 'for i in m' part creates an separate list, one for every k.

M=[list of numbers]
Values=[empty list]

def function(x): 
    
    for k in x:          # Lists in sequence
        for i in m:      # The numbers in each interval in sequence
            Values.append(Polynomial(i))
        return(Values)

function(M)

Upvotes: 0

Views: 472

Answers (1)

Shavk with a Hoon
Shavk with a Hoon

Reputation: 628

Just create a new list (called innerList here) at every iteration of k and append it to your listOfLists which you return.

M=[list of numbers]
Values=[empty list]

def function(x): 
    listOfLists = []
    for k in x:          # Lists in sequence
        innerList = []
        for i in m:      # The numbers in each interval in sequence
            innerList.append(Polynomial(i))
        listOfLists.append(innerList)
    return listOfLists

function(M)

Upvotes: 2

Related Questions