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?
Let us know if you liked the post. That’s the only way we can improve.