Borislav Hadzhiev
Last updated: Jun 16, 2022
Photo from Unsplash
To map over a list and split each string:
split()
method on the list item.my_list = ['a_1', 'b_2', 'c_3'] new_list = [item.split('_') for item in my_list] print(new_list) # 👉️ [['a', '1'], ['b', '2'], ['c', '3']] my_flat_list = [x for xs in new_list for x in xs] print(my_flat_list) # 👉️ ['a', '1', 'b', '2', 'c', '3']
On each iteration, we call the split()
method on the element.
You can optionally flatten the two-dimensional list if you need to.
The str.split() method splits the original 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) |
If the separator is not found in the string, a list containing only 1 element is returned.
Alternatively, you can use the map()
function.
my_list = ['a_1', 'b_2', 'c_3'] new_list = list( map(lambda item: item.split('_'), my_list) ) print(new_list) # 👉️ [['a', '1'], ['b', '2'], ['c', '3']] my_flat_list = [x for xs in new_list for x in xs] print(my_flat_list) # 👉️ ['a', '1', 'b', '2', 'c', '3']
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
However, this is a bit harder to read than using a list comprehension.