Discover Python list multiplication [item] * n to create lists pre-populated with repeated elements.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
Create a function repeat(item, times) that takes an element item and an integer times, returning a list with the item repeated times number of times.
Pre-allocating lists with repeated initial values (like zeroed matrices or default placeholders) is standard practice in algorithm design.
Use Python list multiplication ([item] * times):
def repeat(item, times):
return [item] * times
# Testing our function
print(repeat("edabit", 3)) # Output: ['edabit', 'edabit', 'edabit']
print(repeat(13, 5)) # Output: [13, 13, 13, 13, 13]
print(repeat("7", 2)) # Output: ['7', '7']
print(repeat(0, 0)) # Output: []
Multiplying a 1-element list [item] by integer N creates a new list containing N duplicate shallow references.
[[0] * 3] * 3 creates a 2D matrix where all sub-rows share the SAME inner reference! Mutating row 0 will silently mutate all rows. Use list comprehensions for 2D matrix creation: [[0 for _ in range(3)] for _ in range(3)].Use [item] * n for 1D repeat lists. Next, let's generate even numbers using list comprehensions!