Friday, September 29, 2023

Python - Append item to list N times

For immutable data types:

l = []
x = 0
l.extend([x]*100)
l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)] 
l = [x for i in range(100)]
If you want to add to an existing list, you can use the extend() method of that list
(in conjunction with the generation of a list):
a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]
l.extend([x for i in range(100)])