Reputation: 21971
I have the foll. list in python:
[1, 2, 3, 4]
Is there an python itertools function that results in foll:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
Upvotes: 1
Views: 498
Reputation: 8164
One line solution, using partial and islice,
from itertools import islice
from functools import partial
my_list = [1, 2, 3, 4]
[list(l) for l in map(partial(islice, my_list), range(1,len(my_list)+1))]
you get,
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
in other words,
from itertools import islice
from functools import partial
my_list = [1, 2, 3, 4]
p = partial(islice, my_list)
for i in range(1,5):
print(list(p(i)))
you get,
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
Upvotes: 1
Reputation: 48077
If it is must to use itertools
, you may use itertools.islice
as:
from itertools import islice
my_list = [1, 2, 3, 4]
for i in range(1, len(my_list)+1):
print list(islice(my_list, i))
However there is absolutely no need to use itertools
here. You may achieve this via simple list slicing as:
for i in range(len(my_list)):
print my_list[:i+1]
Both of the above solutions will print the result as:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
Upvotes: 2
Reputation: 214959
This is trivial without itertools:
def fall(it):
ls = []
for x in it:
ls.append(x)
yield ls
for x in fall(xrange(20)):
print x
Note that this works with any iterable, not just a list.
If you still want itertools, something like this should work (py3):
for x in itertools.accumulate(map(lambda x: [x], it)):
print(x)
Again, it's lazy and works with any iterable.
Upvotes: 6
Reputation: 18106
This can be written as one-liner using list comprehension:
>>> [ list[:x+1] for x in range(len(list)) ]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Upvotes: 2
Reputation: 691
You don't need itertools
, just use a map:
>>> l = [1, 2, 3, 4]
>>> for sub_list in map(lambda index: l[:index + 1], range(len(l))):
... print sub_list
Upvotes: 0
Reputation: 113975
There isn't anything in itertools
, that I can think of, but this should work:
def incremental(L):
for i in range(1, len(L)+1):
yield L[:i]
Output:
In [53]: print(*incremental([1, 2, 3, 4]), sep='\n')
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
Upvotes: 3