0

Currently I have a function.

def create1(n): 

    output = []
    for i in range(n):
        output.append(int(i)+1)
    return output

It returns [1,2,3] whenever enter create(3). However, I want it to return [[1],[1,2],[1,2,3]]. I know there's a problem with something in my for loop but I can't figure it out.

1

4 Answers 4

4

Use range() to create lists of numbers quickly:

def create1(n): 
    output = []
    for i in range(n):
       output.append(range(1, i + 2))
    return output

or, using a list comprehension:

def create1(n): 
    return [range(1, i + 2) for i in range(n)]

If you are using Python 3, turn the iterator returned by range() into a list first:

for i in range(n):
   output.append(list(range(1, i + 2)))

Quick demo:

>>> def create1(n): 
...     return [range(1, i + 2) for i in range(n)]
... 
>>> create1(3)
[[1], [1, 2], [1, 2, 3]]
Sign up to request clarification or add additional context in comments.

Comments

3

This works in Python 2 and Python 3:

>>> def create1(n):
...   return [list(range(1,i+1)) for i in range(1,n+1)]
...
>>> create1(5)
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Comments

0

Try this:

def create(n):
    output = []
    for i in range(n):
        output.append(range(1,i+2))
    return output


print create(3)

Comments

0

What you really want is a list appended at every stage. So try this

def create1(n): 
    output = []
    for i in range(n):
        output.append(range(1,i+2)) # append a list, not a number.
    return output

range(n) gives you a list of integers from 0 to n-1. So, at each stage (at each i), you're appending to the output a list from 0 to i+1.

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.