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.

3
  • then what are you expect Commented Jul 29, 2017 at 8:43
  • Possible duplicate of List of lists changes reflected across sublists unexpectedly Commented Jul 29, 2017 at 8:44
  • Because in this case your list consists of 10 references to the list referenced by thing parameter. Commented Jul 29, 2017 at 8:44

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.