In Python, using the * operator (multiplication operator) is the most concise and “Pythonic” way to create a list with specific initial values or to generate a repeating array pattern.
In this article, I will explain how to efficiently expand and initialize lists without using for loops.
Table of Contents
- The Problem to Solve
- Implementation Example: Generating Weekly Shift Patterns
- Source Code
- Execution Result
- Explanation
The Problem to Solve
There are often situations in list initialization where you want to “set all elements to 0” or “repeat a specific pattern (A, B, C) N times.” Writing this with a loop makes the code verbose, so we utilize the operator to write it in a single line.
Implementation Example: Generating Weekly Shift Patterns
Here, we assume a scenario where we define a basic daily shift pattern (Early, Late, Night) and repeat it for one week (7 days) to create a large list.
Source Code
# Basic shift configuration for one day
# Defined as a list of strings
daily_pattern = ["Early", "Late", "Night"]
# Batch generate the schedule slots for one week (7 days)
# By doing [List] * [Integer], the contents of the list are concatenated that many times
weekly_schedule = daily_pattern * 7
# Check the result
print(f"Total shift slots: {len(weekly_schedule)}")
print("--- Generated List ---")
print(weekly_schedule)
Execution Result
Total shift slots: 21
--- Generated List ---
['Early', 'Late', 'Night', 'Early', 'Late', 'Night', 'Early', 'Late', 'Night', 'Early', 'Late', 'Night', 'Early', 'Late', 'Night', 'Early', 'Late', 'Night', 'Early', 'Late', 'Night']
Explanation
List Multiplication
Multiplying a list by an integer N creates a new list where the elements of the original list are repeated N times.
- Single Element Repetition:
[0] * 5→[0, 0, 0, 0, 0]- This is frequently used for array initialization (such as zero-padding).
- Pattern Repetition:
["A", "B"] * 3→["A", "B", "A", "B", "A", "B"]- This is effective when repeating a sequence itself, as in this example.
Important Note: Reference Copy
The elements created by this method are “Shallow Copies.”
This is not a problem for immutable objects like numbers or strings. However, if you put a list inside a list (e.g., [[]] * 3), be careful because all internal lists will refer to the same object. For initializing multi-dimensional arrays, using list comprehension is recommended.
