Python list of identical sublists

list, python

Solution

Use a list comprehension:

[[10, 20] for _ in range(3)]

There is also the option to use multiplication:

[[10, 20]] * 3   # or [pos] * 3

but that creates a list of 3 references to the same nested list:

>>> lis = [[10, 20]] * 3
>>> lis[0][0] = 'foo'
>>> lis
[['foo', 20], ['foo', 20], ['foo', 20]]

which is usually not what you want. The list comprehension re-evaluates the expression on the left hand side (the part before the `for` expression) for each loop iteration and that creates a new list for each index in the outer list:

>>> lis = [[10, 20] for _ in range(3)]
>>> lis[0][0] = 'foo'
>>> lis
[['foo', 20], [10, 20], [10, 20]]

If you want to use a list stored in a variable to repeat, make sure you create a copy on each iteration:

[pos[:] for _ in range(3)]

Problem

I am trying to programmatically create a list containing `n` identical sublists: ``` >>> pos = [10,20] >>> 3 * pos [10, 20, 10, 20, 10, 20] ``` But what I want is `[[10,20], [10,20], [10,20]]` Any clues?

Original source