by 10000truths · 2y ago · 0 comments
[[] for _ in range(N)]
Since generator-like expressions evaluates the inner expression (i.e. the []) on each iteration, the elements of the outer list are guaranteed to be unique references. #good
a = [True] * 8 # bool is primitive
b = [[True] * 8 for i in range(8)] # range creates new lists each time
#bad
a = [{}] * 8 # dict is not a primitive
b = [[True] * 8] * 8 # list is not a primitiveThere just happen to be some types where you cannot change the referenced value in any way. These behave like value types in other languages.
(If you believe that they should be marked explicitly, do you also believe the same thing about Rust? I.e. should the Rust compiler throw an error if you never actually change a reference type, as you "should" be using a value type in that case?)
If you had done [1] * 4 you'd ended up with a list of four references to the same object (1) as well. It's just that 1 isn't mutable, so nobody cares.