Zameer Fouzan
Zameer Fouzan

Reputation: 726

append list B to list A and deleting list B elements for new elements python

I am trying to append data from list B to list A to create list within a list , using listA.append(listB) is not working , i am newbie to python is there anything extra needed to be added?

here is the sample code

`from random import randint
 def call():
     c=0
     a=[]
     b=[]
     while (c != 10):
        b.append(randint(0,9))
        print b
        a.append(b)
        print a
        del b[:]
        c=c+1

 for i in range(2):
    call()`

here is the output

`[7]
 [[7]]
 [3]
 [[3], [3]]
 [3]
 [[3], [3], [3]]
 [8]
 [[8], [8], [8], [8]]
 [0]
 [[0], [0], [0], [0], [0]]
 [7]
 [[7], [7], [7], [7], [7], [7]]
 [3]
 [[3], [3], [3], [3], [3], [3], [3]]
 [9]
 [[9], [9], [9], [9], [9], [9], [9], [9]]
 [2]
 [[2], [2], [2], [2], [2], [2], [2], [2], [2]]
 [1]
 [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
 [8]
 [[8]]
 [0]
 [[0], [0]]
 [0]
 [[0], [0], [0]]
 [6]
 [[6], [6], [6], [6]]
 [2]
 [[2], [2], [2], [2], [2]]
 [7]
 [[7], [7], [7], [7], [7], [7]]
 [9]
 [[9], [9], [9], [9], [9], [9], [9]]
 [7]
 [[7], [7], [7], [7], [7], [7], [7], [7]]
 [6]
 [[6], [6], [6], [6], [6], [6], [6], [6], [6]]
 [1]
 [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]`

i do not understand why is this happening?

Upvotes: 0

Views: 331

Answers (2)

Michael Hoff
Michael Hoff

Reputation: 6318

You always append the same list object b to your list. This means, your list a will contain 10 times the same list object b.

Changed to the contents of b are now reflected to all items in a and this is what you are wondering about.

The following code does what you intend to do.

from random import randint

def call():
    c=0
    a=[]
    while (c != 10):
        b = [] # a new list for each iteration!
        b.append(randint(0,9))
        print b
        a.append(b)
        print a
        c=c+1

for i in range(2):
    call()`

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You aren't appending the contents of b, you're appending b itself. You need to rebind b in the loop rather than just emptying the previous contents.

 ...
print a
b = []
c=c+1

Upvotes: 1

Related Questions