3

I would like to create something like this:

lst = [[None, None], [None, None], [None, None]]

using list comprehensions. However, whatever I try, I find that performing lst[0][0] = True does not have the desired effect. Instead of making the list lst = [[True, None], [None, None], [None, None]], it changes it to lst = [[True, None], [True, None], [True, None]].

Here's the different ways that I've tried creating my list comprehension:

lst = [[None] * 2] * 3
lst = [copy.deepcopy([None] * 2)] * 3
lst = [list([None] * 2])[::]] * 3
Alex Yuwen
  • 31
  • 3

3 Answers3

2

Those are not comprehensions, check this proper comprehension example:

lst = [[None for _ in range(2)] for _ in range(3)]

Here you have a comprehensive documentation for your problem.

Netwave
  • 40,134
  • 6
  • 50
  • 93
0

You may want to use:

l = [[None,None] for i in range(3)]
l[0][0]=True
print(l)
>>> [[True, None], [None, None], [None, None]]
zanga
  • 612
  • 4
  • 20
0

The behavior you're having is due to the way you created your list.

As @Zanga showed, creating the list using list comprehension will not have the same behavior as the way you created it when doing lst[0][0] =True.

Because in the way you created the list ( lst = [[None] * 2] * 3 ), you created a list ( [None, None] ) that you duplicated three time. Then, when trying to modify the first element of the first list, it modifies the first element of all list because there are all duplicates (stored in the same memory location).

Jules Civel
  • 449
  • 2
  • 13