Creating nested Python lists (2D lists) with comprehensions (don't use the product operator!)

preview_player
Показать описание
Lists containing empty (sub)lists can be created efficiently in Python using comprehensions. A common pitfall to avoid is using the product operator; this yields an outer list with several copies of the same inner list. Any element appended to one of the inner list will thus appear to be added to all of them (in fact, they are all the same!). In this video I explain why this happens, and why this procedure would instead work for tuples (though this is not useful in practice). I then show you how to create a list of lists in the proper way, using list comprehensions.

00:00 Introducing lists of lists
00:35 The product trick: take the same element n times
01:00 Why this does not work with inner lists... (a surprising pitfall)
03:30 ...though it would work with inner tuples (but you should not care)
05:44 The proper way: using comprehensions
Рекомендации по теме
welcome to shbcf.ru