Quick Overview
[x] * n repeats the reference rather than the object, so [[]] * 3 produces three names for one list. Mutating one appears to change all three; a comprehension builds distinct objects.
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!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.