Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Nested list comprehensions using deep copies [duplicate]

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
like image 665
Alex Yuwen Avatar asked Jan 19 '26 22:01

Alex Yuwen


1 Answers

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.

like image 140
Netwave Avatar answered Jan 21 '26 12:01

Netwave