2

Hey i was wondering if anyone knew how to create a list of 10 lists of increasing length. The first list should be empty, i.e., len(mylist[0]) == 0; the second list should have one element, so len(mylist[1]) == 1; and so on. I have been trying to use extend,append and insert but to no avail

So far i have been able to create 10 lists with no elements

def mylists(x):    
    d = [[] for x in range(0,x)]
    return d

print (mylists(10)

Any help would be greatly appreciated!

3 Answers 3

1

Try this:

super_list = []
for i in range(10):
    super_list.append(list(range(i))) # .append(range(i)) suffices for python2

You may want to tweak the ranges, depending on your desired outcome. 10 iterations of that will give you ten lists, like so:

[[],
 [0],
 [0, 1],
 [0, 1, 2],
 [0, 1, 2, 3],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4, 5],
 [0, 1, 2, 3, 4, 5, 6],
 [0, 1, 2, 3, 4, 5, 6, 7],
 [0, 1, 2, 3, 4, 5, 6, 7, 8]]

If you feel like doing it in a more functional way, this will achieve the same result in Python 2:

map(range, range(10))

Or in Python 3:

list(map(lambda i: list(range(i)), range(10)))
Sign up to request clarification or add additional context in comments.

3 Comments

Works for python2 only. Python3 will require a conversion to list.
You don't need the lambda. map(range, range(10)) works fine.
Good comments, thanks. Lambda is still needed on Python 3 though, as it has the extra list call.
1

You can do:

print([[i]*i for i in range(10)])

Comments

0
>>> [[i for i in range(n)] for n in range(1,8,1)]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6]]

For using method

>>> def test(n):
...     return [[i for i in range(m)] for m in range(1,n+2,1)]
... 
>>> 
>>> print test(5)
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5]]

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.