[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]?
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.
[1][1][1]?That would be invalid Python syntax.
[1][1] means: "Take list [1] and access index 1"[1] only has one element at index 0[1][1] โ IndexErrorAnd [1][1][1] would continue that and raise another error.
So the format [1][1][1] is not meaningful or valid in Python.
* do with lists?The * operator repeats the elements inside the list.
| Expression | Result | Description |
|---|---|---|
[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 |
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).
| Expression | Output | Meaning |
|---|---|---|
[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 ๐งช