Reputation: 57
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!
Upvotes: 2
Views: 2125
Reputation: 3638
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)))
Upvotes: 1
Reputation: 3523
>>> [[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]]
Upvotes: 0