I know that
[[]] * 10
will give 10 references of the same empty, And
[[] for i in range(10)]
will give 10 empty lists. But in this example:
def get_list(thing):
return [thing for i in range(10)]
a = get_list([])
a[0].append(1)
print(a)
Why the result is again
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
EDIT:
Unlike question List of lists changes reflected across sublists unexpectedly , I understand that Python doesn't do copy in [x]*10.
But why [] is special in [[] for i in range(10)] ? I think this is inconsistent. Instead of creating a empty list [] then pass to [ ___ for i in range(10)], Python take "[]" literally and execute "[]" for every i.
解决方案
That is because thing is the same list.
In [[] for i in range(10)] a new list is generated every time.
In [thing for i in range(10)] it's always the list named thing.