Map over list and split each string in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Map over list and split each string in Python #

To map over a list and split each string:

  1. Use a list comprehension to iterate over the list.
  2. On each iteration, call the split() method on the list item.
  3. The result will be a two-dimensional list.
main.py
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']
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 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:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt 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.

main.py
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.

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.