How to join specific list elements in Python


Borislav Hadzhiev

Sat Jun 18 20222 min read


Photo by Chad Madden

Join specific list elements in Python #

To join specific list elements in Python:

  1. Use list slicing to select the specific elements in the list.
  2. Use the str.join() method to join the elements into a string.
  3. Replace the list elements with the string.
my_list = ['ab', 'cd', 'ef', 'gh', 'ij'] my_list[1:3] = [''.join(my_list[1:3])] print(my_list) # 👉️ ['ab', 'cdef', 'gh', 'ij']

The syntax for list slicing is my_list[start:stop:step].

We only provided values for start and stop.

Note that the value for start is inclusive, whereas the value for stop is exclusive.

So we start selecting list items at index 1 (cd) and go up to but not including the list item at index 3 (gh).

We used the str.join() method to join the subset of elements.
my_list = ['ab', 'cd', 'ef', 'gh', 'ij'] print(''.join(my_list[1:3])) # 👉️ 'cdef'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The last step is to replace the same subset of elements with the string.

The string the join() method is called on is used as the separator between elements. We didn't provide one in the example but you can specify a separator if you need to.

If you don't want to mutate the contents of the original list, use the copy() method to create a shallow copy of the list.
my_list = ['ab', 'cd', 'ef', 'gh', 'ij'] my_copy = my_list.copy() my_copy[1:3] = [''.join(my_copy[1:3])] # 👇️ copy list updated print(my_copy) # 👉️ ['ab', 'cdef', 'gh', 'ij'] # 👇️ original list remains unhanged print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh', 'ij']

The example changes the contents of the copy and keeps the original list the same.

If you don't know the index of the values you need to join in the list, use the list.index() method.
my_list = ['ab', 'cd', 'ef', 'gh', 'ij'] start = my_list.index('cd') stop = my_list.index('ef') + 1 my_list[start:stop] = [''.join(my_list[start:stop])] print(my_list) # 👉️ ['ab', 'cdef', 'gh', 'ij']

The list.index() method returns the index of the first item whose value is equal to the provided argument.

We added 1 to the index of the string ef because the stop index is exclusive.

Note that the str.join() method raises a TypeError if there are any non-string values in the iterable.

If your list contains numbers, or other types, convert all of the values to string before calling join().
my_list = ['ab', 'cd', 123, 'gh', 'ij'] my_list[1:3] = [''.join(map(str, my_list[1:3]))] print(my_list) # 👉️ ['ab', 'cd123', 'gh', 'ij']

We used the map() function to convert all list items to strings before passing the result to the str.join() method.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

Use the search field on my Home Page to filter through my more than 1,000 articles.