Home > Back-end >  Problem in creating a 2D list with n rows in python
Problem in creating a 2D list with n rows in python

Time:01-28

I want to create an empty 2D list in python so in any row I can add multiple tuples as I want ex. [ [ (2,3)] , [ (4,5) ,(6,5) ,(9,0)] ] I only know that rows of the list will be n. and after that I can manually append tuples as per the question. so I tried to create 2D list using:

L = [ []*n ]  # n is number of rows ex. n = 5
print(L)      # It gives [[]] instead of [[], [], [], [], []]

Why?

CodePudding user response:

[] * n duplicates the elements present inside the list. Since your list is empty, [] * n evaluates to [].

Additionally, [[]] * n will yield [[],[],[],[],[] for n = 5, but attempting to append an element to any of the inner lists will cause all the lists to contain the same element.

>>> L = [[]]* 5
>>> L[0].append(1)
>>> L
[[1], [1], [1], [1], [1]]

This is due to the fact that each element of the outer list is essentially a reference to the same inner list.

Therefore, the idiomatic way to create such a list of lists is

L = [[] for _ in range(n)]

CodePudding user response:

use this code to create a 2D array:

L = [[] for _ in range(n)]
  •  Tags:  
  • Related