cybertron15
cybertron15

Reputation: 3

append method in python not working as expected in nested for loops

I want to append a list into another list using nested for loops but the code is not working as expected

def apend():
    ls = []
    numbers = [0,0]
    
    for num1 in range(3):
        for num2 in range(2):
            numbers[0] = num1
            numbers[1] = num2
            ls.append(numbers)
    print(ls)

apend()

I expect the output to be: [[0,0],[0,1],[0,2],1,0],[1,1],[1,2]]

but i get this output: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]

Upvotes: 0

Views: 2352

Answers (4)

furas
furas

Reputation: 142651

If you run your code on http://pythontutor.com/ then you see

enter image description here

All elements in list ls keep reference to the same list numbers and this makes problem.

You have to create new list numbers = [0,0] inside for-loop

for num1 in range(3):
    for num2 in range(2):
        numbers = [0,0]
        numbers[0] = num1
        numbers[1] = num2
        ls.append(numbers)

Or simply do it without numbers

for num1 in range(3):
    for num2 in range(2):
        ls.append([num1, num2])

Upvotes: 2

Prabhu Teja
Prabhu Teja

Reputation: 21

You can do it it in this way :

def apend():
    ls=[]
    numbers=[0,0]
    for num1 in range(3):
        for num2 in range(2):
            numbers[0]=num1
            numbers[1]=num2
            ls.append(num.copy())
    print(ls)
apend()

Upvotes: 0

hochae
hochae

Reputation: 109

You are appending the list named numbers in the loop. Just append a new list object as below.

def apend():
    ls = []
    numbers = [0,0]
    
    for num1 in range(3):
        for num2 in range(2):
            numbers[0] = num1
            numbers[1] = num2
            ls.append(list(numbers)) # append a new list object 
    print(ls)

By the way, I'd like to use list comprehension for this function.

def append():
    ls = [[x, y] for x in range(3) for y in range(2)]
    print(ls)

Upvotes: 0

noob_to_so
noob_to_so

Reputation: 55

Just change the numbers to numbers[:] and you will get you output as expected.

ls.append(numbers) means you are appending the reference of the list . so when the list changes , all instace changes . when you do ls.append(numbers[:]) this appends a copy of numbers.

def apend():
    ls = []
    numbers = [0,0]
    
    for num1 in range(3):
        for num2 in range(2):
            numbers[0] = num1
            numbers[1] = num2
            ls.append(numbers[:])
    print(ls)

apend()

Upvotes: 1

Related Questions