2

I think similar questions exist but I can't seem to find them out

x=list(([],)*3)
x[0].append(1)
x[1].append(2)
x[2].append(3)
print(x)

I want the result to look like this:

[[1],[2],[3]]

But instead, I get:

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Also I really don't want to use any loops but if it is necessary then I'll try

Owen Sam
  • 29
  • 1
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – no comment Nov 24 '21 at 17:42

3 Answers3

2

Just realized you don't want to use a for loop.

Option 1: no for loops:

x = []
x.append([1])
x.append([2])
x.append([3])
print(x)
> [[1], [2], [3]]

Option 2: using loops.

Easiest and cleanest way is to use list comprehension like this:

x = [[i] for i in range(1,4)]
print(x)
> [[1], [2], [3]]

Or you can use a plain for loop and create an empty list before:

result = []
for i in range(1,4):
    result.append([i])
result
FredMaster
  • 1,211
  • 1
  • 15
  • 35
1

Instead of the first line, use

x = [[] for _ in range(3)]

In the current code, x is a list of the empty lists which are actually the same object. That's how [...] * n works; it repeats the same objects n times. So appending an item to one of these empty lists would append the item to the others, because they are the same.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

You can create an empty list first and starts appending each element as a list.

x=[]
x.append([1])
x.append([2])
x.append([3])
print(x)