How to Split the elements of a List in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Table of Contents

  1. Split the elements of a list in Python
  2. Splitting each element in a list into nested Lists
  3. Split each element in a List into nested Lists and flatten the result
  4. Split a List every N items in Python
  5. Split a List every N items using a for loop
  6. Splitting a specific list item
  7. Split a list using numpy.array_split
  8. Split a List based on a condition in Python
  9. Split a List based on a condition using a list comprehension

# Split the elements of a list in Python

To split the elements of a list in Python:

  1. Use a list comprehension to iterate over the list.
  2. On each iteration, call the split() method to split each string.
  3. Return the part of each string you want to keep.
main.py
my_list = ['a-1', 'b-2', 'c-3', 'd-4'] result = [item.split('-', 1)[0] for item in my_list] print(result) # ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

split elements in list

The code for this article is available on GitHub

The example shows how to split each element in the list and only keep the first part.

If you need to get the second part after splitting, use an index of 1.

main.py
my_list = ['a-1', 'b-2', 'c-3', 'd-4'] result = [item.split('-', 1)[1] for item in my_list] print(result) # ๐Ÿ‘‰๏ธ ['1', '2', '3', '4'] # -------------------------------------------- # ๐Ÿ‘‡๏ธ if you need to convert strings to numbers list_of_ints = [int(x) for x in result] print(list_of_ints) # ๐Ÿ‘‰๏ธ [1, 2, 3, 4]

get second part after splitting

We used a list comprehension to iterate over the list.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

We passed 1 for the maxsplit argument to only split the string once and get the first item.

If you need to split the string on each occurrence of the delimiter, remove the second argument in the call to str.split().

main.py
# ๐Ÿ‘‡๏ธ ['a', 'b.c.d'] print('a.b.c.d'.split('.', 1)) # ๐Ÿ‘ˆ๏ธ with maxsplit set to 1 # ๐Ÿ‘‡๏ธ ['a', 'b', 'c', 'd'] print('a.b.c.d'.split('.')) # ๐Ÿ‘ˆ๏ธ without maxsplit

split on each occurrence of delimiter

# Splitting each element in a list into nested Lists

The second example splits each element in the list into nested lists.

main.py
my_list = ['a-1', 'b-2', 'c-3', 'd-4'] result = [item.split('-') for item in my_list] # ๐Ÿ‘‡๏ธ [['a', '1'], ['b', '2'], ['c', '3'], ['d', '4']] print(result)

split each element in list into nested list

The code for this article is available on GitHub

You can also flatten the list after you split each string.

main.py
my_list = ['a-1', 'b-2', 'c-3', 'd-4'] # โœ… Split each element in the list and flatten the list result = [item.split('-') for item in my_list] result_flat = [item for l in result for item in l] # ๐Ÿ‘‡๏ธ ['a', '1', 'b', '2', 'c', '3', 'd', '4'] print(result_flat)

The result variable is a two-dimensional list, so we had to use another list comprehension to flatten it.

# Split each element in a List into nested Lists and flatten the result

You can achieve the same result by using a for loop.

main.py
my_list = ['a-1', 'b-2', 'c-3', 'd-4'] # โœ… split each element in the list and flatten the list result = [item.split('-') for item in my_list] # ๐Ÿ‘‡๏ธ [['a', '1'], ['b', '2'], ['c', '3'], ['d', '4']] print(result) result_flat = [] for l in result: for item in l: result_flat.append(item) # ๐Ÿ‘‡๏ธ ['a', '1', 'b', '2', 'c', '3', 'd', '4'] print(result_flat)

split each element in list and flatten

The code for this article is available on GitHub

We used a nested for loop to flatten a list of lists.

The outer for loop is used to iterate over the two-dimensional list.

In order to get access to the items in the nested lists, we need a nested for loop.

On each iteration, we append each list item into an empty list.

# Split a List every N items in Python

To split a list every N items:

  1. Use the range() class to iterate over a range with step X.
  2. On each iteration, return a list slice from the current index until the index + X.
main.py
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 result = [ my_list[idx:idx+n] for idx in range(0, len(my_list), n) ] # ๐Ÿ‘‡๏ธ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] print(result)

split list every n items

The code for this article is available on GitHub

We used the range() class to iterate over a range with a step of N.

main.py
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 # ๐Ÿ‘‡๏ธ [0, 2, 4, 6, 8] print(list(range(0, len(my_list), n)))

The range() class is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

The indexes in the range are the indexes of the first list item in each nested list.

On each iteration, we get a slice that starts at the current index and ends at the current index + N.

The example above uses a list comprehension to iterate over the range.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

# Split a List every N items using a for loop

You can also use a for loop to achieve the same result.

main.py
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 result = [] for idx in range(0, len(my_list), n): result.append(my_list[idx:idx+n]) # ๐Ÿ‘‡๏ธ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] print(result)
The code for this article is available on GitHub

This for loop is the equivalent of the list comprehension we previously used.

# Splitting a specific list item

If you need to split a list item, access the list at the specific index before calling the split() method.

main.py
my_list = ['a-1', 'b-2', 'c-3', 'd-4'] result = my_list[0].split('-') print(result) # ๐Ÿ‘‰๏ธ ['a', '1'] print(result[0]) # ๐Ÿ‘‰๏ธ a print(result[1]) # ๐Ÿ‘‰๏ธ 1 # ๐Ÿ‘‡๏ธ ['b', '2'] print(my_list[1].split('-'))

Indexes are zero-based in Python, so the first item in a list has an index of 0, the second an index of 1, etc.

# Split a list using numpy.array_split

You can also use the numpy.array_split() method to split a list.

main.py
import numpy as np a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # โœ… split a list into 4 subarrays of equal size arr = np.array_split(a_list, 4) # [array(['a', 'b', 'c'], dtype='<U1'), # array(['d', 'e', 'f'], dtype='<U1'), # array(['g', 'h'], dtype='<U1'), # array(['i', 'j'], dtype='<U1')] print(arr) for item in arr: # ['a' 'b' 'c'] # ['d' 'e' 'f'] # ['g' 'h'] # ['i' 'j'] print(item)
The code for this article is available on GitHub

The array_split method splits an array into multiple sub-arrays.

The first argument the method takes is an array-like object and the second argument is into how many subarrays we want to split the list.

We split the list into 4 subarrays of equal size in the example.

If you need to install the NumPy module in the environment, run the following command from your terminal.

shell
pip install numpy # ๐Ÿ‘‡๏ธ with pip3 pip3 install numpy

# Split a list based on a condition in Python

To split a list based on a condition:

  1. Declare two new variables and initialize them to empty lists.
  2. Use a for loop to iterate over the original list.
  3. Check if each item meets a condition.
  4. Append the items that meet the condition to one list and the ones that don't to the other.
main.py
my_list = [1, 21, 3, 7, 14, 28, 35] lte_10 = [] gte_10 = [] for item in my_list: if item <= 10: lte_10.append(item) else: gte_10.append(item) print(lte_10) # ๐Ÿ‘‰๏ธ [1, 3, 7] print(gte_10) # ๐Ÿ‘‰๏ธ [21, 14, 28, 35]
The code for this article is available on GitHub

We used a for loop to iterate over the list.

On each iteration, we check if the current item is less than or equal to 10.

If the condition is met, we append the item to the lte_10 list, otherwise, we append the item to the gte_10.

You can also use an elif clause if you have to.

main.py
my_list = [1, 21, 3, 7, 14, 19, 28, 35] lte_10 = [] gte_10 = [] between_10_and_20 = [] for item in my_list: if item <= 10: lte_10.append(item) elif item > 10 and item < 20: between_10_and_20.append(item) else: gte_10.append(item) print(lte_10) # ๐Ÿ‘‰๏ธ [1, 3, 7] print(gte_10) # ๐Ÿ‘‰๏ธ [21, 28, 35] print(between_10_and_20) # ๐Ÿ‘‰๏ธ [14, 19]

The elif statement checks if the current item is greater than 10 and less than 20.

If the condition is met, we append the value to the third list.

Alternatively, you can use a list comprehension.

# Split a list based on a condition using a list comprehension

This is a three-step process:

  1. Use a list comprehension to iterate over the list.
  2. Check if each item meets a condition.
  3. The new list will only contain the items that meet the condition.
main.py
my_list = [1, 21, 3, 7, 14, 19, 28, 35] lte_10 = [ item for item in my_list if item <= 10 ] print(lte_10) # ๐Ÿ‘‰๏ธ [1, 3, 7] gte_10 = [ item for item in my_list if item >= 10 ] print(gte_10) # ๐Ÿ‘‰๏ธ [21, 14, 19, 28, 35]
The code for this article is available on GitHub

We used two list comprehensions to iterate over the list.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if a condition is met and return the matching item.

The new lists only contain the elements that meet the condition.

You can use this approach to check for any condition.

I've also written an article on how to split a string into fixed-size chunks.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev