How to Split a List in Python?

Recently, in a Python webinar, someone asked me a question about splitting lists. After researching and testing various methods, I found a few important methods to achieve this task. In this tutorial, I will explain how to split a list in Python with suitable examples and screenshots.

Split a List in Python

One of the simplest ways to split a list in Python is by using the slicing operator (:). Slicing allows you to extract a portion of a list by specifying the start and end indices. Here’s an example:

states = ["California", "Texas", "Florida", "New York", "Illinois", "Pennsylvania", "Ohio", "Georgia", "North Carolina", "Michigan"]

west_coast = states[:3]
east_coast = states[3:6]
midwest = states[6:]

print("West Coast states:", west_coast)
print("East Coast states:", east_coast)
print("Midwest states:", midwest)

Output:

West Coast states: ['California', 'Texas', 'Florida']
East Coast states: ['New York', 'Illinois', 'Pennsylvania']
Midwest states: ['Ohio', 'Georgia', 'North Carolina', 'Michigan']

You can see this in the screenshot below.

Split a List in Python

In this example, we split the states list into three sublists using slicing:

  • west_coast: Contains the first three elements of the states list (indices 0 to 2).
  • east_coast: Contains the next three elements (indices 3 to 5).
  • midwest: Contains the remaining elements (index 6 to the end).

Slicing is a quick and easy way to split a list when you know the specific indices you want to use for the split. Slicing is the simplest way to split a list in Python.

Read How to Print Lists in Python?

1. Use a Specific Value

Sometimes, you may want to split a list based on a specific value rather than using indices. For example, let’s say you have a list of US state information where each element contains the state name and its capital, separated by a tab character:

state_info = ["California\tSacramento", "Texas\tAustin", "Florida\tTallahassee", "New York\tAlbany", "Illinois\tSpringfield"]

To split this list into separate lists for state names and capitals, you can use the split() method with the tab character as the delimiter:

state_names = []
state_capitals = []

for info in state_info:
    name, capital = info.split("\t")
    state_names.append(name)
    state_capitals.append(capital)

print("State names:", state_names)
print("State capitals:", state_capitals)

Output:

State names: ['California', 'Texas', 'Florida', 'New York', 'Illinois']
State capitals: ['Sacramento', 'Austin', 'Tallahassee', 'Albany', 'Springfield']

You can see this in the screenshot below.

How to Split a List in Python

In this example, we iterate through each element of the state_info list, split it at the tab character, and append the resulting state name and capital to separate lists.

Check out How to Convert a List to a Set in Python?

2. Use List Comprehension

List comprehension is a concise and efficient way to create new lists based on existing lists. You can use list comprehension to split a list by applying a condition or transformation to each element. Here’s an example:

names = ["John Smith", "Emily Johnson", "Michael Davis", "Emma Brown", "Christopher Wilson"]

first_names = [name.split()[0] for name in names]
last_names = [name.split()[-1] for name in names]

print("First names:", first_names)
print("Last names:", last_names)

Output:

First names: ['John', 'Emily', 'Michael', 'Emma', 'Christopher']
Last names: ['Smith', 'Johnson', 'Davis', 'Brown', 'Wilson']

You can see this in the screenshot below.

Split a List in Python list comprehension

In this example, we have a list of full names (names). We use list comprehension to split each name into its first and last name components:

  • first_names: We apply name.split()[0] to each name in the names list, extracting the first element of the resulting split (the first name).
  • last_names: We apply name.split()[-1] to each name, extracting the last element of the resulting split (the last name).

Read How to Get Unique Values from a List in Python?

Advanced List Splitting Techniques

Let us learn some important advanced list splitting techniques:

Split a List into Chunks of Equal Size

Sometimes, you may need to split a list into chunks of equal size. For example, if you have a large dataset of US cities and want to process them in smaller batches. Python’s built-in zip() function, along with the iter() function and list slicing, can be used to achieve this. Here’s an example:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"]

def split_into_chunks(lst, chunk_size):
    return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]

city_chunks = split_into_chunks(cities, 3)

print("City chunks:")
for chunk in city_chunks:
    print(chunk)

Output:

City chunks:
['New York', 'Los Angeles', 'Chicago']
['Houston', 'Phoenix', 'Philadelphia']
['San Antonio', 'San Diego', 'Dallas']
['San Jose']

In this example, we define a function called split_into_chunks() that takes a list (lst) and a chunk size (chunk_size) as arguments. The function uses list comprehension to create a new list of sublists, where each sublist contains chunk_size elements from the original list.

We then call split_into_chunks() with the cities list and a chunk size of 3, splitting the list into chunks of 3 cities each. The resulting city_chunks list contains the sublists of cities.

Check out How to Replace Values in a List Using Python?

Split a List Based on a Condition

In some cases, you may want to split a list based on a specific condition. For example, let’s say you have a list of US states and their populations, and you want to split the list into two sublists: one for states with a population above a certain threshold and another for states below that threshold.

state_populations = [
    ("California", 39512223),
    ("Texas", 28995881),
    ("Florida", 21477737),
    ("New York", 19453561),
    ("Illinois", 12671821),
    ("Pennsylvania", 12801989),
    ("Ohio", 11689100),
    ("Georgia", 10617423),
    ("North Carolina", 10488084),
    ("Michigan", 9986857)
]

threshold = 15000000

high_population_states = [state for state in state_populations if state[1] > threshold]
low_population_states = [state for state in state_populations if state[1] <= threshold]

print("High population states:")
for state in high_population_states:
    print(state)

print("\nLow population states:")
for state in low_population_states:
    print(state)

Output:

High population states:
('California', 39512223)
('Texas', 28995881)
('Florida', 21477737)
('New York', 19453561)

Low population states:
('Illinois', 12671821)
('Pennsylvania', 12801989)
('Ohio', 11689100)
('Georgia', 10617423)
('North Carolina', 10488084)
('Michigan', 9986857)

In this example, we have a list of tuples called state_populations where each tuple contains a state name and its population. We define a population threshold of 15,000,000.

We use list comprehension to create two new lists:

  • high_population_states: Contains states with a population above the threshold.
  • low_population_states: Contains states with a population less than or equal to the threshold.

We then print the resulting sublists, separating the high and low population states.

Read How to Shuffle a List in Python?

Conclusion

In this tutorial, I explored various techniques to split a list in Python. I discussed using the slicing operator (:) , using a specific value , and using list comprehension. I also covered advanced list splitting techniques, such as splitting a list into chunks of equal size and splitting a list based on a condition.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.