[Python] How to Repeatedly Generate and Initialize List Elements

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

  1. The Problem to Solve
  2. Implementation Example: Generating Weekly Shift Patterns
  3. Source Code
  4. Execution Result
  5. 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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次