Skip to main content

How to Split Lists in Python: Basic Examples and Advanced Methods

Learn how to split Python lists with techniques like slicing, list comprehensions, and itertools. Discover when to use each method for optimal data handling.
Jun 21, 2024  · 11 min read

Python lists are dynamic mutable array data types used to store ordered items. Splitting lists is a common task in Python, essential for manipulating and analyzing data efficiently. 

You can learn more about data analysis by taking the Data Analyst with Python career track to sharpen your skills, which dives into the various methods to split lists in Python, including practical examples and best practices. 

Mastering these techniques will enhance your coding skills, making your scripts more efficient and maintainable. Let’s get started.

The Quick Answer: How to Split a List in Python

  • 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. 

  • The rest of this article explores other methods to split a list, including list comprehensions, itertools, numpy, and more. Each method has unique advantages and is suited for different use cases, as we will see.

The most common method: split a list using slicing

Python split list at index is likely the most common split list technique. The slicing method ensures the Python list is split into sublists at the specified index. Here is a step-by-step guide on how to implement slicing in Python.

  • Define the List: Suppose you have a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and you want to split it at a specific index n.
  • Identify the Split Index: Specify the index n where you want to slice the list.
  • Create the First Slice: In the code below, create first_slice to contain elements from the beginning of the list up to, but not including, index n.
  • Create the Second Slice: Define second_slice to include all elements from index n to the end of the list.
# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Index where the list will be split
n = 4

# Slice the list from the beginning to the nth index (not inclusive)
first_slice = my_list[:n]

# Slice the list from the nth index to the end
second_slice = my_list[n:]

# Print the first slice of the list
print("First slice:", first_slice)  # Output: [1, 2, 3, 4]

# Print the second slice of the list
print("Second slice:", second_slice)  # Output: [5, 6, 7, 8, 9, 10]

Example output of Python split list through slicing

Example output of Python split list through slicing. Image by Author

Understanding List Splitting in Python

List slicing in Python involves extracting a sublist or sublists from the main list. When you want to split a list in Python, you must understand the slicing syntax to understand the proper sublist better. The slicing syntax includes a start, stop, and step.

# Example of slicing with start, stop, and step
slice[start:stop:step]
  1. Start indicates the start of the index of the slicing.
  2. Stop indicates the end of the index of the slicing
  3. Step indicates the intervals between slicing (1 by default).
# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list from index 2 to 7 (index 2 inclusive, index 7 exclusive)
# This will include elements at index 2, 3, 4, 5, and 6
sublist = my_list[2:7]

# Print the sliced sublist
print(sublist) 

According to the above code, the slicing starts from index 2 to index 6 since the sublist does not include index 7.

Example output of slicing syntax.  Image by Author

Example output of slicing syntax. Image by Author

The benefits of Python split list in code readability and efficiency include:

  • Simplifying Data Management: By splitting data into manageable chunks, data scientists can easily separate training and testing data in machine learning.
  • Increasing Modularity: Writing functions with specific sublists enhances modularity in your code.
  • Optimizing Performance: Using smaller list chunks results in faster processing compared to using whole lists.
  • Enhancing Memory Efficiency: The method creates chunks without copying the underlying data, making it memory efficient.

Different Techniques to Split Lists in Python

There are different methods on how to split a list in Python. Below are common examples a data practitioner may encounter during their practice.

Using list slicing

Python split list slicing uses the operator : to split the list at the index. This method utilizes the indexing technique to specify the start and end of slicing.

The different techniques for slicing include the following:

Positive index slicing

This method uses the positive indices values, starting from left to right from left to right, to access the elements in the list.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list from index 2 to 7 (index 2 inclusive, index 7 exclusive)
# This will include elements at index 2, 3, 4, 5, and 6
sublist = my_list[2:7]

# Print the sliced sublist
print(sublist) 

Example output of slicing syntax using positive indices.

Example output of slicing syntax using positive indices. Image by Author

Negative index slicing

This Python split list method uses the negative indices values starting from the last element in the list, right to left.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list to get the last 5 elements
sublist = my_list[-5:]

# Print the sliced sublist containing the last 5 elements
print(sublist)

# Slice the list to get all elements except the last 3
sublist = my_list[:-3]

# Print the sliced sublist containing all but the last 3 elements
print(sublist)

Example output of slicing syntax using negative indices.

Example output of slicing syntax using negative indices. Image by Author

Using step method

This approach uses specific conditions to split the list when accessing different elements.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list to get every second element, starting from the beginning
sublist = my_list[::2]

# Print the sliced sublist containing every second element
print(sublist) 

# Slice the list to get every second element, starting from index 1
sublist = my_list[1::2]

# Print the sliced sublist containing every second element, starting from index 1
print(sublist) 

# Slice the list to get the elements in reverse order
sublist = my_list[::-1]

# Print the sliced sublist containing the elements in reverse order
print(sublist) 

Example output of slicing syntax using the step method.

Example output of slicing syntax using the step method.  Image by Author

Omitting indices

This method slices the Python list by returning only the required elements in a list.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list from the start to index 5 (index 5 not inclusive)
sublist = my_list[:5]

# Print the sliced sublist containing elements from the start to index 4
print(sublist) 

# Slice the list from index 5 to the end
sublist = my_list[5:]

# Print the sliced sublist containing elements from index 5 to the end
print(sublist) 

# Slice the list to get the entire list
sublist = my_list[:]

# Print the sliced sublist containing the entire list
print(sublist) 

Example output of slicing syntax by omitting indices.

Example output of slicing syntax by omitting indices.  Image by Author

Using list comprehensions

Python list comprehension allows one to split list into chunks based on the values of the existing list.

# Define a function to split a list into chunks of a specified size
def split_list(lst, chunk_size):
    # Use a list comprehension to create chunks
    # For each index 'i' in the range from 0 to the length of the list with step 'chunk_size'
    # Slice the list from index 'i' to 'i + chunk_size'
    return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Split the list into chunks of size 3 using the split_list function
chunks = split_list(my_list, 3)

# Print the resulting list of chunks
print(chunks)

The above code uses Python split list into n chunks of size three to return a new list with chunk lists of 3 values.

Example output of Python split list using split comprehension

Example output of Python split list using split comprehension. Image by Author

Using Itertools

Python split list using itertools uses the Python module to transform data through iteration.

# Import the islice function from the itertools module
from itertools import islice
# Define a function to yield chunks of a specified size from an iterable
def chunks(iterable, size):
    # Create an iterator from the input iterable
    iterator = iter(iterable)
    
    # Loop over the iterator, taking the first element in each iteration
    for first in iterator:
        # Yield a list consisting of the first element and the next 'size-1' elements from the iterator
        yield [first] + list(islice(iterator, size - 1))

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Convert the generator returned by the chunks function into a list of chunks
chunked_list = list(chunks(my_list, 3))

# Print the resulting list of chunks
print(chunked_list)

Example output of Python split list using itertools

Example output of Python split list using itertools. Image by Author

Using numpy

The numpy library in Python is useful for splitting arrays to sublists. The .array_split() function allows splits when specifying the number of splits.

# Import the numpy library and alias it as np
import numpy as np

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Use numpy's array_split function to split the list into 3 chunks
chunks = np.array_split(my_list, 3)

# Convert each chunk back to a regular list and print the resulting list of chunks
print([list(chunk) for chunk in chunks])

Example output of Python split list using numpy

Example output of Python split list using numpy. Image by Author

Splitting lists into chunks

The following Python function also allows one to split a list into chunks. These chunks could be custom depending on the number a user requires.

# Define a function to split a list into chunks of a specified size
def split_into_chunks(lst, chunk_size):
    chunks = []  # Initialize an empty list to store chunks
    
    # Iterate over the list with a step of chunk_size
    for i in range(0, len(lst), chunk_size):
        # Slice the list from index 'i' to 'i + chunk_size' and append it to chunks
        chunks.append(lst[i:i + chunk_size])
    
    return chunks  # Return the list of chunks

# Define a list of integers from 1 to 16
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

# Split the list into chunks of size 4 using the split_into_chunks function
chunks = split_into_chunks(my_list, 4)

# Print the resulting list of chunks
print(chunks)

Example output of Python split list into chunks

Example output of Python split list into chunks. Image by Author

Splitting lists based on conditions

When you want to split a list in Python, you can set some rules/conditions for the sublist. This method allows you to create a sublist that meets these conditions.

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# List comprehension to filter elements divisible by 3
div_3 = [x for x in my_list if x % 3 == 0]

# List comprehension to filter elements not divisible by 3
not_div_3 = [x for x in my_list if x % 3 != 0]

# Print the list of elements divisible by 3
print(div_3)

# Print the list of elements not divisible by 3
print(not_div_3)

Example output of Python split list based on conditions

Example output of Python split list based on conditions. Image by Author

Using for loops

For loops can also be used to split lists in Python based on conditions and through iteration.

# Define a function to split a list into sub-lists of size n
def split_by_n(lst, n):
    # Use a list comprehension to create sub-lists
    # For each index 'i' in the range from 0 to the length of the list with step 'n'
    # Slice the list from index 'i' to 'i + n'
    return [lst[i:i + n] for i in range(0, len(lst), n)]

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Split the list into sub-lists of size 5 using the split_by_n function
sub_lists = split_by_n(my_list, 5)

# Print the resulting list of sub-lists
print(sub_lists) 

Example output of Python split list using for loops

Example output of Python split list using for loops. Image by Author

Using the zip() function

You can also use the zip() function in Python to split list through pairing.

# Define two lists: list1 containing integers from 1 to 10, and list2 containing letters from 'a' to 'j'
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

# Use the zip function to pair corresponding elements from list1 and list2 into tuples
paired = list(zip(list1, list2))

# Print the list of paired tuples
print(paired)

Example output of Python split list using zip() function

Example output of Python split list using zip() function. Image by Author

Using the enumerate() function

The enumerate() function splits the Python lists using index conditions. This function uses iteration to split a list into equal chunks.

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Define the chunk size for splitting the list
chunk_size = 5

# Create a list of empty lists, one for each chunk
split_list = [[] for _ in range(chunk_size)]

# Iterate over the elements and their indices in my_list
for index, value in enumerate(my_list):
    # Calculate the index of the sublist where the current value should go using modulo operation
    sublist_index = index % chunk_size
    
    # Append the current value to the corresponding sublist in split_list
    split_list[sublist_index].append(value)

# Print the list of sublists after splitting my_list into chunks
print(split_list)

Example output of Python split list using enumerate() function

Example output of Python split list using enumerate() function. Image by Author

Python split string to list

Using the split() method

The split() method splits a string into a list in Python, given a specified delimiter. The method returns the substrings according to the number of delimiters in the given string.

# Define a string
myString = "Goodmorning to you"

# Split the string into a list of words based on whitespace (default separator)
my_list = myString.split()

# Print the resulting list
print(my_list) 

Example output of split string to list Python using split() method

Example output of split string to list Python using split() method. Image by Author

Using splitlines() method

The splitlines() method splits string into list Python based on the new line character.

# Define a string with newline characters
myString = "Goodmorning\nto\nyou"

# Split the string into a list of lines based on newline characters
my_list = myString.splitlines()

# Print the resulting list
print(my_list)

Example output of split string to list Python using splitlines() method

Example output of split string to list Python using splitlines() method. Image by Author

Using partition() method

The partition() method splits strings into lists in Python using the given separator. This method returns three parts; the string before the separator, the separator, and everything after the separator as a list.

# Define a string with a delimiter '/'
myString = "Goodmorning/to you"

# Use the partition() method to split the string into three parts based on the first occurrence of '/'
my_list = myString.partition('/')

# Print the resulting tuple
print(my_list)  # Output: ('Goodmorning', '/', 'to you')

Example output of split string list Python using partition() method

Example output of split string list Python using partition() method. Image by Author

Using regular expressions

In Python, regular expressions can also be used to split a string into a list. The example below shows how to do this using whitespace.

# Import the 're' module for regular expressions
import re

# Define a string
myString = "Goodmorning to you"

# Use re.split() to split the string based on whitespace ('\s' matches any whitespace character)
# Returns a list of substrings where the string has been split at each whitespace
my_list = re.split('\s', myString)

# Print the resulting list
print(my_list)

Example output of split string list Python using regular expressions.

Example output of split string list Python using regular expressions. Image by Author

Comparison table

Here is a table so you can see at a glance when different techniques might be useful. Practically speaking, the same technique might work for many cases without pronounced differences in performance, so the callouts for when a particular technique is most useful might be somewhat exaggerated. 

Technique Use Case When It's Useful
Slicing Splitting a list at a specific index or range of indices. Useful for simple, straightforward splits.
List Comprehensions Creating sublists based on the values or conditions in the list. Useful for more complex criteria-based splitting.
itertools.islice Splitting a list into chunks of a specified size using an iterator. Useful for handling large lists efficiently.
numpy.array_split Splitting arrays into sublists based on the number of desired splits. Useful for handling numerical data efficiently.
Condition-Based Splitting Splitting a list based on conditions such as divisibility. Useful for separating data into meaningful sublists.
For Loops Iterating through a list to create sublists of a specific size. Useful for more control over the splitting process.
zip() Function Pairing elements from two lists. Useful for combining data from two related lists.
enumerate() Function Splitting lists using index conditions, often for equal-sized chunks. Useful for creating equally distributed sublists.
split() Method Splitting strings into lists based on a specified delimiter. Useful for text data processing.
splitlines() Method Splitting strings into lists based on newline characters. Useful for reading text data with multiple lines.
partition() Method Splitting strings into three parts based on a specified separator. Useful for specific text processing scenarios.
Regular Expressions Using regex to split strings into lists based on complex patterns. Useful for advanced text data manipulation.

Become a ML Scientist

Master Python skills to become a machine learning scientist
Start Learning for Free

Common Pitfalls and How to Avoid Them

A data practitioner may encounter some common errors when handling split lists in Python. Below are some of the common pitfalls and how to avoid them.

Off-by-one errors

The off-by-one error occurs during basic slicing when you include fewer or more indices than required in the list.

my_list = [1, 2, 3, 4, 5]

# Trying to get sublist from index 2 to 4, inclusive
sublist = my_list[2:5]  # Correct: my_list[2:5]
print(sublist)  # Output: [3, 4, 5]

# Incorrect usage:
sublist = my_list[2:4]  # Incorrect, excludes index 4
print(sublist)  # Output: [3, 4]

To avoid this error, understand the indexing sequence in Python and know what to include or exclude when indexing.

Errors with packages used

You may also encounter errors with the packages, especially when the split method requires Python modules. Examples include the numpy, re, and itertools packages. To avoid this error, ensure the packages are properly loaded and used as compatible versions.

Handling edge cases

Edge cases may occur in Python list split when you fail to account for some scenarios. For example, the snippet below indicates a function trying to split lists into chunks of 5 when the list contains only 4 items.

import numpy as np

my_list = [1, 2, 3, 4]
chunks = np.array_split(my_list, 5)
print(chunks)

To avoid this error, use conditional statements to handle the edge case, as shown below.

import numpy as np

my_list = [1, 2, 3, 4]
if len(my_list) < 5:
    chunks = [my_list]
else:
    chunks = np.array_split(my_list, 5)
print(chunks)

Handling special characters

Failing to handle special characters properly may also result in errors when splitting string lists in Python. These special characters include white spaces, commas, or alpha-numerics.

The example below shows how to avoid this error by specifying the character to split the string list.

# Example list with special characters
my_list = ["apple, orange", "dog, mouse", "green, blue"]

# Splitting each string by the comma
split_list = [s.split(",") for s in my_list]
print(split_list)

Best Practices and Guidelines

Since split list in Python is a common operation in data analysis, it is important to adhere to some practices to ensure efficiency. These recommendations include;

  • Maintain Immutability Where Possible: If the original list should not be modified, ensure that your slicing operations do not alter the original list. Slicing creates new lists, so this is usually not an issue, but be aware of it when working with more complex data structures.
  • Optimize for Performance: When dealing with large lists, be mindful of performance implications. Slicing is generally efficient, but unnecessary copying of large lists can lead to performance bottlenecks.
  • Handle Edge Cases: Consider edge cases such as an empty list, splitting at the start or end of the list, and invalid indices. Ensure your code can handle these scenarios gracefully.
  • Include Error Handling and Validation: Error handling is especially important when you want to split a list into multiple lists in Python, so your code doesn’t break and create surprises. 

DataCamp’s Python Programming course offers a detailed explanation of the best practices to write code efficiently, considering common concepts like error handling and performance. 

Advanced List Splitting Techniques

Splitting lists can be taken to an advanced level by utilizing various methods that offer more control and flexibility. 

Split list into multiple lists

You can split the Python list into multiple lists by specifying the split at specific indices. For example, the code below splits the list at the following index 2, 5, 7.

def split_at_indices(lst, indices):
    result = []
    prev_index = 0
    for index in indices:
        result.append(lst[prev_index:index])
        prev_index = index
    result.append(lst[prev_index:])
    return result

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
indices = [2, 5, 7]
split_lists = split_at_indices(my_list, indices)
print(split_lists)

Example output of Python split list into multiple lists.

Example output of Python split list into multiple lists. Image by Author

Split list into equal parts

You can also use an in-built library like ‘numpy’ to split a Python list into equal parts based on the number of parts you want.

import numpy as np

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
num_parts = 3
split_lists = np.array_split(my_list, num_parts)
print([list(arr) for arr in split_lists])

Split a list in half

One can use slicing to split Python list into half.

def split_in_half(lst):
    # Calculate the midpoint index of the list
    mid_index = len(lst) // 2
    # Return the two halves of the list
    return lst[:mid_index], lst[mid_index:]

# Example list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Split the list into two halves
first_half, second_half = split_in_half(my_list)
print(first_half)
print(second_half)

In the case of a list with an odd number of elements, you can specify the index to include in the first half.

def split_in_half(lst):
    # Calculate the midpoint index of the list, including the middle element in the first half if the length is odd
    mid_index = (len(lst) + 1) // 2
    # Return the two halves of the list
    return lst[:mid_index], lst[mid_index:]

# Example list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Split the list into two halves, handling odd-length
first_half, second_half = split_in_half(my_list)
print(first_half) 
print(second_half) 

The Python Developer also offers insights on how to write advanced code that will help you to understand advanced list-splitting techniques.

Conclusion

There are different methods for splitting lists in Python. Each method depends on the type of list and the user’s preference for efficiency. As a data practitioner, selecting the appropriate split list method that suits your analysis is important.

For a thorough understanding of the Python split list, you can learn more from our course, Python Fundamentals. You can also take the Introduction to Python course to ensure you master operating on lists and other data types in Python. The Python Cheat Sheet for Beginners also comes in handy when you want to have a glance at how to split a list in Python.

Become an ML Scientist

Upskill in Python to become a machine learning scientist.

Allan Ouko's photo
Author
Allan Ouko
LinkedIn
I create articles that simplify data science and analytics, making them easy to understand and accessible.

Frequently Asked Questions

When would I need to split a list in Python?

Python split list is important for data processing, especially when managing large datasets. The transformations help when you split data to perform analysis, such as training and testing machine learning models.

What should I do if the itertools and numpy modules return an error?

Ensure you have the appropriate Python libraries installed. If the error persists, ensure you update and use the compatible versions of the libraries.

What is the difference between splitting a Python list and partition()?

The partition() method returns three tuples where the conditional argument is in the middle.

Can I split a Python list with a specific delimiter or given value?

You need to specify the given delimiter or value to split the list.

How do I ensure I improve the performance of my code when I split a list into multiple lists?

Use a reusable function when splitting a list into multiple lists. This approach ensures efficiency.

Topics

Learn Python with DataCamp

Course

Introduction to Functions in Python

3 hr
443.2K
Learn the art of writing your own functions in Python, as well as key concepts like scoping and error handling.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Tutorial

Python Slice: Useful Methods for Everyday Coding

Discover how slicing can effortlessly extract, rearrange, and analyze your data. Harness negative indices, multi-dimensional slices, and advanced step values for full precision.
Oluseye Jeremiah's photo

Oluseye Jeremiah

8 min

Tutorial

String Split in Python Tutorial

Learn how you can perform various operations on string using built-in Python functions like split, join and regular expressions.
DataCamp Team's photo

DataCamp Team

2 min

Tutorial

Python Reverse List: How to Reorder Your Data

Choose the right Python list reversal technique between reverse(), slicing, reversed(), and list comprehensions. Use these methods to tackle tasks like data sorting and sequence alignment.
Oluseye Jeremiah's photo

Oluseye Jeremiah

5 min

Tutorial

Python List Functions & Methods Tutorial and Examples

Learn about Python List functions and methods. Follow code examples for list() and other Python functions and methods now!
Abid Ali Awan's photo

Abid Ali Awan

7 min

Tutorial

Python List Comprehension Tutorial

Learn how to effectively use list comprehension in Python to create lists, to replace (nested) for loops and the map(), filter() and reduce() functions, ...!
Aditya Sharma's photo

Aditya Sharma

14 min

Tutorial

Python Copy List: What You Should Know

Understand how to copy lists in Python. Learn how to use the copy() and list() functions. Discover the difference between shallow and deep copies.
Allan Ouko's photo

Allan Ouko

7 min

See MoreSee More