2

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.

flm8620
  • 1,411
  • 11
  • 15

2 Answers2

5

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.

Bharel
  • 23,672
  • 5
  • 40
  • 80
0

I now understand why I'm wrong. I answer my question:

I misunderstood the list comprehension in python

[ ___ for i in range(10)]

It's not like passing a augment to a function. List comprehension execute your expression literally each time in its loop.

The expression [] in [ [] for i in range(10)] is executed each time so you get a new empty list for each entry.

Same for [thing for i in range(10)]. expression thing is executed, and the result is alway the same: a reference to one empty list.

flm8620
  • 1,411
  • 11
  • 15