0

I have a lists of list, and I would like to append data to each sublist independently. When I append to one, it seems like ALL of the sublists are getting the same data appended. Here is my code:

Code:

parent = [[]] * 2
data = [1]*4
parent[0].append(data)
print "sublist 0:", parent[0]
print "sublist 1:", parent[1]

Output:

sublist 0: [[1, 1, 1, 1]]
sublist 1: [[1, 1, 1, 1]]

Expected Output:

sublist 0: [[1, 1, 1, 1]]
sublist 1: []

What am I doing wrong or not understanding here?

benathon
  • 7,455
  • 2
  • 41
  • 70
  • 1
    I think this post may help you. http://stackoverflow.com/questions/8177079/python-take-the-content-of-a-list-and-append-it-to-another-list – Jimmy Feb 08 '17 at 23:53
  • 1
    Jimmy, My question is a duplicate, all the answers there will help me. To change my code all I need to do is `parent = [[] for _ in range(2)]` – benathon Feb 08 '17 at 23:55
  • Initiating is different from constructing. a = [[]] * 2 # here initiated a list and assigned to a. b = [[] for _ in range(2)] # here constructing a list and assigning to b. – Amitkumar Karnik Feb 09 '17 at 10:30

0 Answers0