Initializing a 2D List in Python

  • Python

Incorrect:

A 2D list CANNOT be initialized like this:

my2dList = [[]] * 5
# this gives you [[], [], [], [], []]

The problem is that the five []s are referring (pointing) to the same [] instance.
That is, if you change one, others will be affected as well.

Correct:

A correct way is as follows:

my2dList = [ [] for i in range(5) ]
# this still gives you [[], [], [], [], []]

This time, all five []s are different instances and are independent.

Was this post helpful?

Leave a Reply

Your email address will not be published.