0

How can ı change this code to make list like [[0],[0,1],[0,1,2]]

a=[]
lst = 3
element = 1
for i in range(lst):
    a.append([0,1,2] * element)
print(a)

output = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

2 Answers 2

2

You need to build up the content of a little by little.

For example, this would work as follows:

a=[]
lst = 3
element = 1
x = []
for i in range(lst):
    x = x + [i]
    a.append(x * element)
print(a)

Thus, the value of i is always extended to x and written to a.

Sign up to request clarification or add additional context in comments.

Comments

1

The change that works while changing the least amount of code:

a.append( [0,1,2][:i+1]* element) # only change this line

A better approach would probably be to use a list comprehension. The whole code will then be something like:

n = 3
my_list = [0,1,2]
output = [my_list[:i] for i in range(1,n+1)]
print(output)

output:

[[0], [0, 1], [0, 1, 2]]

4 Comments

input —> 3,4 output —> [[0,0,0,0],[0,1,2,3],[0,2,4,6]]
ım new to python and couldn't do this output
ım trying to keep the 0 same but +1 the others
What is the logic behind the desired result? why would an input of 3,4 correspond to that output? 3 will be the number of sublists I think, but what does an input of 4 mean?

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.