Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create all sequences from the first item within a list

Tags:

python

Say I have a list, ['a', 'b', 'c', 'd']. Are there any built-ins or methods in Python to easily create all contiguous sublists (i.e. sub-sequences) starting from the first item?:

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']

in Python?

Note that I am excluding lists/sequences such as ['a' ,'c'], ['a', 'd'], ['b'], ['c'] or ['d']

like image 476
Josh Avatar asked Nov 18 '25 06:11

Josh


2 Answers

To match your example output (prefixes), then you can just use:

prefixes = [your_list[:end] for end in xrange(1, len(your_list) + 1)]
like image 187
Jon Clements Avatar answered Nov 20 '25 20:11

Jon Clements


You can do this with a simple list comprehension:

>>> l = ['a', 'b', 'c', 'd']
>>> 
>>> [l[:i+1] for i in range(len(l))]
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]

See also: range()

If you're using Python 2.x, use xrange() instead.

like image 37
arshajii Avatar answered Nov 20 '25 20:11

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!