Last updated: Apr 8, 2024
Reading timeยท7 min
To split the elements of a list in Python:
split()
method to split each string.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']
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
.
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]
We used a list comprehension to iterate over the list.
The str.split() method splits the string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At 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()
.
# ๐๏ธ ['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
The second example splits each element in the list into nested lists.
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)
You can also flatten the list after you split each string.
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.
You can achieve the same result by using a for
loop.
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)
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.
for
loop.On each iteration, we append each list item into an empty list.
To split a list every N items:
range()
class to iterate over a range with step X.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)
We used the range()
class to iterate over a range with a step of N.
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:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range 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.
for
loopYou can also use a for
loop to achieve the same result.
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)
This for
loop is the equivalent of the list comprehension we previously used.
If you need to split a list item, access the list at the specific index before
calling the split()
method.
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.
numpy.array_split
You can also use the numpy.array_split() method to split a list.
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 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.
pip install numpy # ๐๏ธ with pip3 pip3 install numpy
To split a list based on a condition:
for
loop to iterate over the original list.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]
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.
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.
This is a three-step process:
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]
We used two list comprehensions to iterate over the list.
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.
You can learn more about the related topics by checking out the following tutorials: