Issue while appending item in list in a list in python

Viewed 59

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

3 Answers

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

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.

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)
Related