'Split a list into sub-lists based on index ranges

How do I split a list into sub-lists based on index ranges?

e.g. original list:

list1 = [x,y,z,a,b,c,d,e,f,g]

using index ranges 0–4:

list1a = [x,y,z,a,b]

using index ranges 5–9:

list1b = [c,d,e,f,g]

I already known the (variable) indices of list elements which contain certain string and want to split the list based on these index values.

Also need to split into variable number of sub-lists, i.e.:

list1a
list1b
.
.
list1[x]


Solution 1:[1]

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

Solution 2:[2]

In python, it's called slicing. Here is an example of python's 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.

Solution 3:[3]

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 we're adding +1 to the end to make the range inclusive...

Solution 4:[4]

list1a=list[:5]
list1b=list[5:]

Solution 5:[5]

One of the ways to do it if you have multiple indexes or know the range of indexes you need to get:

split_points - points where you will split your string or list

k - the range you need to split, example = 3

split_points = [i for i in range(0, len(string), k)]

parts = [string[ind:ind + k] for ind in split_points]

Solution 6:[6]

list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]

Solution 7:[7]

Consider the core pesudocode of the following example:

def slice_it(list_2be_sliced, indices):
    """Slices a list at specific indices into constituent lists.
    """
    indices.append(len(list_2be_sliced))
    return [list_2be_sliced[indices[i]:indices[i+1]] for i in range(len(indices)-1)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Jon Clements
Solution 4 no1
Solution 5 Chris_007
Solution 6
Solution 7 Shady