1

While trying to append values to a nested list through a for loop, I came across an issue that the appending values to the list depends on the way the list is initialized.Suppose, I initialize a nested array as:

    a=[[[],[],[],[]],[[],[],[],[],[]]]
    a[0][1].append(2)

results in

    [[[], [2], [], []], [[], [], [], [], []]]

but initializing and appending data in the following manner

    a= [[[]]*4]*2
    a[0][1].append(2)

results in

    [[[2], [2], [2], [2]], [[2], [2], [2], [2]]]

What is the difference between the two as both of them initialize the same type of list?

  • 1
    When using asterisk `*` it multiplies the empty list into many. So when appending, all the lists that are multiplied, gets appended – PCM Jun 04 '21 at 04:52
  • `[x]*n` creates a list with *n references to the same object*. Copies aren't made. So, `x = []`, then `a = [x, x, x]`, then try `a[0].append(2)` and see the result – juanpa.arrivillaga Jun 04 '21 at 04:54
  • When you do the following: ``a=[[[],[],[],[]],[[],[],[],[],[]]] a[0][1].append(2) # result - > [[[], [2], [], []], [[], [], [], [], []]]`` it results in the above because you are taking the 0th element of list a and then appending 2 at the 1st location. but doing something like this ``a = []*3`` will create a 3 elements in the list a ``a = [ , , ]`` similarly if you do something like this ``a = [10]*3`` it will create ``a = [10, 10, 10]`` – Cool Breeze Jun 04 '21 at 04:55
  • Got it. Thanks. But is there a way to get around it? – Srivastava Shobhit Jun 04 '21 at 04:58
  • `[[[] for _ in range(4)] for _ in range(2)]` – juanpa.arrivillaga Jun 04 '21 at 05:00

0 Answers0