0

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?

0

2 Answers 2

2

[] * 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)]

Sign up to request clarification or add additional context in comments.

Comments

1

use this code to create a 2D array:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.