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

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thanks !! Didn't thought about list comprehension
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.