# ๐Ÿ” Why `[1] * 3` gives `[1, 1, 1]` instead of `[1][1][1]` in Python?

Yeeunยท2025๋…„ 4์›” 16์ผ

Python

๋ชฉ๋ก ๋ณด๊ธฐ
6/31

๐Ÿ” Why [1] * 3 gives [1, 1, 1] instead of [1][1][1] in Python?

When I saw the code below for the first time:

[self.constant] * len(X)

I thought it would return something like this:

[1][1][1]

But instead, the actual result was:

[1, 1, 1]

So I wanted to figure out: Why is the output a flat list, and not nested or separate elements like [1][1][1]?


โœ… Whatโ€™s really happening?

Letโ€™s walk through a real example.

self.constant = 1
X = [10, 20, 30]

Then:

[self.constant] * len(X)
โ†’ [1] * 3
โ†’ [1, 1, 1]

It creates a single list with the value 1 repeated three times.


โ“Why not [1][1][1]?

That would be invalid Python syntax.

  • [1][1] means: "Take list [1] and access index 1"
  • But [1] only has one element at index 0
  • So [1][1] โ†’ IndexError

And [1][1][1] would continue that and raise another error.

So the format [1][1][1] is not meaningful or valid in Python.


๐Ÿ”„ So what does * do with lists?

The * operator repeats the elements inside the list.

ExpressionResultDescription
[1] * 3[1, 1, 1]Repeats value 1 three times
["hi"] * 2["hi", "hi"]Repeats string "hi" twice
[[1]] * 3[[1], [1], [1]]Repeats the inner list

โœ… Want a list of lists?

Then use a list comprehension like this:

[[self.constant] for _ in range(len(X))]

That gives:

[[1], [1], [1]]

Each [1] is a new list, so they are not shared references (important for avoiding bugs later).


๐Ÿง  Summary

ExpressionOutputMeaning
[1] * 3[1, 1, 1]One list, repeating values
[[1]] * 3[[1], [1], [1]]One list, repeating sublists (but be careful: they point to the same object)
[[1] for _ in range(3)][[1], [1], [1]]Three new lists, each with one element

Hope this clears things up!
Let me know if you want to dive into shared references or memory issues with list multiplication. Thatโ€™s a fun next step ๐Ÿงช

0๊ฐœ์˜ ๋Œ“๊ธ€