Skip to content Skip to sidebar Skip to footer

Python List Of List Initialize

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

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Python List Of List Initialize"