Python: Split a list into sub-lists based on index ranges

Python: Split a list into sub-lists based on index ranges

In python, its called slicing. Here is an example of pythons slice notation:

>>> list1 = [a,b,c,d,e,f,g,h, i, j, k, l]
>>> print list1[:5]
[a, b, c, d, e]
>>> print list1[-7:]
[f, g, h, i, j, k, l]

Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.

Note that you can use a variable in a slice:

l = [a, b, c, d, e]
c_index = l.index(c)
l2 = l[:c_index]

This would put the first two entries of l in l2

Python: Split a list into sub-lists based on index ranges

If you already know the indices:

list1 = [x,y,z,a,b,c,d,e,f,g]
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]

Note that were adding +1 to the end to make the range inclusive…

Leave a Reply

Your email address will not be published.