Create List of Single Item Repeated n Times in Python
Depending on your use-case, you want to use different techniques with different semantics.
Multiply a list for Immutable items
For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:
[e] * 4
For example:
>>> [None] * 4
[None, None, None, None]
Note that this is usually only used with immutable items (strings, tuples, frozensets, etc) in the list, because they all point to the same item in the same place in memory.
For an example use-case, I use this when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.
schema = ['string'] * len(columns)
Multiply the list where we want the same item with mutable state repeated
Multiplying a list gives us the same elements over and over. The need for this is infrequent:
[iter(iterable)] * 4
This is sometimes used to map an iterable into a list of lists:
>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)] # uninteresting usage
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
We can see that a_list
contains the same range iterator four times:
>>> from pprint import pprint
>>> pprint(a_list)
[<range_iterator object at 0x7f9fe3b58420>,
<range_iterator object at 0x7f9fe3b58420>,
<range_iterator object at 0x7f9fe3b58420>,
<range_iterator object at 0x7f9fe3b58420>]
Mutable items
I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.
Instead, to have repeated, say, a mutable empty list, set, or dict, you should do something like this:
list_of_lists = [[] for _ in iterator_of_needed_length]
The underscore is simply a throwaway variable name in this context.
If you only have the number, that would be:
list_of_lists = [[] for _ in range(4)]
The _
as the throwaway name is not really special, but a static code analyzer will probably complain if you don't intend to use the variable and use any other name.
Caveats for using the multiplication method with mutable items:
Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:
foo = [[]] * 4
foo[0].append('x')
foo now returns:
[['x'], ['x'], ['x'], ['x']]
But with immutable objects, you can make it work because you change the reference, not the object:
>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]
>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]
But again, mutable objects are no good for this, because in-place operations change the object, not the reference:
l = [set()] * 4
>>> l[0] |= set('abc')
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]