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.

Answer from TerryA on Stack Overflow
🌐
DataCamp
datacamp.com › tutorial › python-split-list
How to Split Lists in Python: Basic and Advanced Methods | DataCamp
June 21, 2024 - The simplest way to split a list in Python is by slicing with the : operator. For example, we can split a list in this way: split_list = my_list[:5], which splits the list at the fifth index.
Discussions

python - Splitting a list by indexes - Code Review Stack Exchange
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am trying to build an efficient function for splitting a list of any size by any given number of indices. This method works and it took me a few hours to get it right (I hate how easy it is to get things wrong when using indexes... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
June 30, 2016
Split a list into parts based on a set of indexes in Python - Stack Overflow
What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below ... If there are no indexes it should return the entire list. ... I'm mildly interested in your answer-selection criteria ... simpler and faster are not "Pythonic"? More on stackoverflow.com
🌐 stackoverflow.com
python - Splitting a list or list of lists by index - Stack Overflow
I want to split list at index i of list: input_list = `['book flight from Moscow to Paris for less than 200 euro no more than 3 stops', 'Moscow', 'Paris', '200 euro', '3']` My required output: More on stackoverflow.com
🌐 stackoverflow.com
python - Splitting a string by list of indices - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I want to split a string by a list of indices, where the split segments begin with one index and end before the next one. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › how do i split a list every 2 indexes
r/learnpython on Reddit: How do I split a list every 2 indexes
August 2, 2022 -

Hello I have a list of integers:

trackIndex = [0, 22, 23, 58, 59,79,80,100,101,122]

These serve as indexes for another list of strings from a text file and I only need to extract certain indexes.

strings = [ "sentence 1", "sentence 2","sentence 3","sentence 4"....]

How can I loop through trackIndex and split it every two indexes (i.e. [0,22], [23,58],[59,79],[80, 100], [101,122] and then take those to extract those indexes from the "strings list" and store it in a new list called "newList"?

🌐
GeeksforGeeks
geeksforgeeks.org › python › split-a-python-list-into-sub-lists-based-on-index-ranges
Split a Python List into Sub-Lists Based on Index Ranges - GeeksforGeeks
July 23, 2025 - List comprehension is the most efficient way to split a list into sub-lists based on index ranges. It uses Python’s built-in slicing mechanism to extract segments concisely. This method is ideal for small to medium-sized lists where readability ...
🌐
datagy
datagy.io › home › python posts › python lists › python: split a list (in half, in chunks)
Python: Split a List (In Half, in Chunks) • datagy
December 30, 2022 - We also declare a variable, chunk_size, which we’ve set to three, to indicate that we want to split our list into chunks of size 3 · We then loop over our list using the range function. What we’ve done here is created items from 0, through to the size of our list, iterating at our chunk size. For example, our range function would read range(0, 11, 3), meaning that we’d loop over using items 0,3,6,9. We then index our list from i:i+chunk_size, meaning the first loop would be 0:3, then 3:6, etc.
Top answer
1 of 3
17

There is a lot simpler way to do this. You can use list slicing and the zip function.

List slicing essentially cuts up a given list into sections. The general form is list[start:stop:step]. The start section of a slice designates the first index of the list we want to included in our slice. The stop section designates the first index of the list we want excluded in our slice. The step section defines how many indices we are moving as well as in which direction (based on whether it is positive or negative). An example:

>>> x = [1, 2, 3, 4]
>>> x[1:3]
[2, 3]
>>> x[2:]
[3, 4]
>>> x[0:4]
[1, 2, 3, 4]
>>> x[0:4:1]
[1, 2, 3, 4]
>>> x[0:4:2]
[1, 3]
>>> x[0:4:3]
[1, 4]
>>> x[0:4:4]
[1]
>>> x[0:4:5]
[1]

The zip function takes sequences and creates a zip object that contains tuples of their corresponding index elements:

>>> for pair in zip([1, 2, 3], ['a', 'b', 'c']):
...    print(pair)
(1, 'a')
(2, 'b')
(3, 'c')

You can combine these two strategies to simplify your function. Here is my version of your lindexsplit function:

def lindexsplit(some_list, *args):
    # Checks to see if any extra arguments were passed. If so,
    # prepend the 0th index and append the final index of the 
    # passed list. This saves from having to check for the beginning
    # and end of args in the for-loop. Also, increment each value in 
    # args to get the desired behavior.
    if args:
        args = (0,) + tuple(data+1 for data in args) + (len(some_list)+1,)

    # For a little more brevity, here is the list comprehension of the following
    # statements:
    #    return [some_list[start:end] for start, end in zip(args, args[1:])]
    my_list = []
    for start, end in zip(args, args[1:]):
        my_list.append(some_list[start:end])
    return my_list

2 of 3
5

A few cosmetic changes to makes your code more beautiful/pythonic :

Fix formatting

  • Remove some line breaks as it makes the code harder to read
  • Change variables name to follow PEP 8
  • Your code lacks documentation making it hard to understand.

Use enumerate

Enumerate does exactly what you are trying to achieve : keep track of the index while looping on an iterable. Just use for indexofitem,item in enumerate(List):.

Remove levels of nested logic

Using elif, you could make your code a bit easier to follow. The inside of the for-loop becomes :

    if breakcounter <= numberofbreaks:
        if indexofitem < nextbreakindex:
            templist1.append(item)
        elif breakcounter < (numberofbreaks - 1):
            templist1.append(item)
            templist2.append(templist1)
            templist1 = []
            breakcounter +=1
        elif indexofitem <= lastindexval and indexofitem <= totalitems:
            templist1.append(item)
            templist2.append(templist1)
            templist1 = []
        elif indexofitem >= lastindexval and indexofitem < totalitems + 1:
            finalcounter += 1
            templist3.append(item)
            if finalcounter == finalcounttrigger:
                templist2.append(templist3)

Rewrite your comparisons

In Python, you can write comparisons in a very natural way : indexofitem >= lastindexval and indexofitem < totalitems + 1 becomes lastindexval <= indexofitem < totalitems + 1.

Use smart indices to get the last element of array

You can rewrite lastindexval = index[(len(index)-1)] with the much clearer lastindexval = index[-1].

Rethink your logic

You have totalitems = len(List) and indexofitem going from 0 to len(List) - 1 (included). Thus, indexofitem <= totalitems is not an interesting condition to check. The same goes for indexofitem < totalitems + 1.

Once this is removed, we have :

    #Less than the last cut
    if breakcounter <= numberofbreaks:
        if indexofitem < nextbreakindex:
            templist1.append(item)
        elif breakcounter < (numberofbreaks - 1):
            templist1.append(item)
            templist2.append(templist1)
            templist1 = []
            breakcounter +=1
        elif indexofitem <= lastindexval:
            templist1.append(item)
            templist2.append(templist1)
            templist1 = []
        elif lastindexval <= indexofitem:
            finalcounter += 1
            templist3.append(item)
            if finalcounter == finalcounttrigger:
                templist2.append(templist3)

Re-think your logic (bis)

On the code above, the last 2 elif checks are a bit redundant : if we don't go into the indexofitem <= lastindexval block then we must have lastindexval < indexofitem and ``lastindexval <= indexofitem` must be true.

After cleaning this, the code looks like :

    for indexofitem,item in enumerate(List):
        nextbreakindex = index[breakcounter]

        #Less than the last cut
        if breakcounter <= numberofbreaks:
            if indexofitem < nextbreakindex:
                templist1.append(item)
            elif breakcounter < (numberofbreaks - 1):
                templist1.append(item)
                templist2.append(templist1)
                templist1 = []
                breakcounter +=1
            elif indexofitem <= lastindexval:
                templist1.append(item)
                templist2.append(templist1)
                templist1 = []
            else:
                finalcounter += 1
                templist3.append(item)
                if finalcounter == finalcounttrigger:
                    templist2.append(templist3)
    return templist2

Re-think your logic (ter)

Nothing happens in the loop if breakcounter > numberofbreaks as breakcounter and numberofbreaks are not changed. If this is really the case, we might as well just break out of the loop. However, things are even better than this : once again we are in a situation that cannot happen. This can be seen in two different ways :

  • if breakcounter was to be bigger than numberofbreaks, nextbreakindex = index[breakcounter] would have thrown an exception.

  • breakcounter only gets incremented one element at a time. This happens only if breakcounter < (numberofbreaks - 1). Thus, once breakcounter reaches numberofbreaks - 1, it stops growing.

At the end of this rewriting, your code looks like :

def lindexsplit(List,*lindex):
    index = list(lindex)
    index.sort()

    templist1 = []
    templist2 = []
    templist3 = []

    breakcounter = 0
    finalcounter = 0

    numberofbreaks = len(index)

    lastindexval = index[-1]
    finalcounttrigger = (len(List)-(lastindexval+1))

    for indexofitem,item in enumerate(List):
        nextbreakindex = index[breakcounter]

        if indexofitem < nextbreakindex:
            print "A"
            templist1.append(item)
        elif breakcounter < (numberofbreaks - 1):
            print "B"
            templist1.append(item)
            templist2.append(templist1)
            templist1 = []
            breakcounter +=1
        elif indexofitem <= lastindexval:
            print "C"
            templist1.append(item)
            templist2.append(templist1)
            templist1 = []
        else:
            print "D"
            finalcounter += 1
            templist3.append(item)
            if finalcounter == finalcounttrigger:
                templist2.append(templist3)
    return templist2

I reckon there is still a lot more to improve and a much more simple solution could be written (as suggested in the comments).

🌐
Coding-engineer
coding-engineer.com › 2023 › 04 › 14 › split-python-list-into-sublists-base-on-index-indices
Split Python List into sublists base on index/indices
April 13, 2023 - #It has to be a common occurance for all the sub-lists for item in reviews_list: index += 1 if (delimiter_text in item ) : index_list.append(index) #remove last element(last index). #Since the split will occur at the index ie happen before 'End of review' # hence we +1 to make the split after 'End of review' index_list.pop() index_list = [item +1 for item in index_list] print (index_list) #Split List into sublists reviews_sublist = [sublist.tolist() for sublist in np.split(reviews_list, index_list)] print(reviews_sublist) #Print sublist as independent lists for sublist in reviews_sublist: print(sublist) print('\n')
Find elsewhere
🌐
Altcademy
altcademy.com › blog › how-to-split-a-list-in-python
How to split a list in Python - Altcademy.com
June 13, 2023 - Slicing allows us to extract a ... syntax for slicing is list[start:end], where start is the index of the first element you want to include and end is the index of the first element you want to exclude....
🌐
TutorialsPoint
tutorialspoint.com › custom-list-split-in-python
Custom list split in Python
May 4, 2020 - data_list = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] # The indexes to split at split_points = [2, 5, 8] # Given list print("Given list : " + str(data_list)) # Split at print("The points of splitting : ", split_points) # Perform the split split_list = [data_list[i: j] for i, j in zip([0] + split_points, split_points + [None])] # printing result print("The split lists are : ", split_list)
🌐
Python Guides
pythonguides.com › split-a-string-by-index-in-python
How To Split A String By Index In Python?
January 27, 2026 - Sometimes “splitting by index” actually means you want every single character on its own. In Python, you don’t even need a special function for this. You can simply use the list() constructor.
🌐
GeeksforGeeks
geeksforgeeks.org › python-custom-list-split
Python | Custom list split | GeeksforGeeks
April 6, 2023 - # Python3 code to demonstrate # to perform custom list split # using list comprehension + zip() # initializing string test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4] # initializing split index list split_list = [2, 5, 7] # printing original list print (&quot;The original list is : &quot; + str(test_list)) # printing original split index list print (&quot;The original split index list : &quot; + str(split_list)) # using list comprehension + zip() # to perform custom list split res = [test_list[i : j] for i, j in zip([0] + split_list, split_list + [None])] # printing result print (&quot;The splitted lists are : &quot; + str(res))
🌐
Bobby Hadz
bobbyhadz.com › blog › python-split-elements-in-list
How to Split the elements of a List in Python | bobbyhadz
If you need to split a list item, access the list at the specific index before calling the split() method. main.py · Copied!my_list = ['a-1', 'b-2', 'c-3', 'd-4'] result = my_list[0].split('-') print(result) # 👉️ ['a', '1'] print(result[0]) ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-split-lists-in-python
How to Split Lists in Python? - GeeksforGeeks
July 23, 2025 - Let's explore different methods to split lists in Python. The simplest way to split a list is by using slicing. This method allows you to divide a list into fixed-size chunks by specifying start and end indices.
🌐
GeeksforGeeks
geeksforgeeks.org › python-split-list-into-lists-by-particular-value
Split list into lists by value - Python - GeeksforGeeks
April 28, 2025 - This can be achieved by iterating over the dictionary, slicing each list up to the k-th index and storing the result in a new dictionary. For example, given a ... Sometimes, while working with Python tuples, we can have a problem in which we ...
🌐
Delft Stack
delftstack.com › home › howto › python › split list in half in python
How to Split Python List in Half | Delft Stack
February 2, 2024 - We created a function split_list that returns two halves of an existing list. Note that it does not change the original list, as it creates a duplicate list to perform the assigned task. In Python, itertools is the inbuilt module allowing us to handle the iterators efficiently.
🌐
Finxter
blog.finxter.com › home › learn python blog › python | split string by list of indices
Python | Split String by List of Indices - Be on the Right Side of Change
December 8, 2022 - Note that appending a “None” to the indices list ensures that last section of the substring (starting from index 7 until end of string) is taken into account and the split operation is performed accurately. In absence of None the script won’t be able to slice the string in the last iteration and you won’t be able to fetch the last part of the string. The above solution can be formulated in a more compact way using a list comprehension as shown in the solution below: ... text = "I want to learn Python" indices = [0, 2, 7] indices.append(None); [print([text[indices[i]:indices[i+1]] for i in range(len(indices)-1)])]
🌐
Stack Overflow
stackoverflow.com › questions › 23212581 › python-function-to-split-a-list-by-indexes
python function to split a list by indexes - Stack Overflow
Copyindex = list(lindex) index.sort() templist1 = [] templist2 = [] templist3 = [] breakcounter = 0 itemcounter = 0 finalcounter = 0 numberofbreaks = len(index) totalitems = len(List) lastindexval = index[(len(index)-1)] finalcounttrigger = (totalitems-(lastindexval+1)) for item in List: itemcounter += 1 indexofitem = itemcounter - 1 nextbreakindex = index[breakcounter] #Less than the last cut if breakcounter <= numberofbreaks: if indexofitem < nextbreakindex: templist1.append(item) elif breakcounter < (numberofbreaks - 1): templist1.append(item) templist2.append(templist1) templist1 = [] brea