Python Join List Slice

Rate this post

To join and replace all strings in a list lst between start index 1 and end index 5, use the one-liner lst[1:5] = [''.join(lst[1:5])]. This solution is based on slice assignment that selects the slice you want to replace on the left and the values to replace it on the right side of the assignment.

Problem: Given a list of strings. How to join all strings in a given list slice and replace the slice with the joined string?

Example:You start with the following list:

lst = ['i', 'l', 'o', 'v', 'e', 'u']

You want to join the slice ['l', 'o', 'v', 'e'] with start index 1 and end index 4 (included) and replace it in the list to obtain the result:

# Output: ['i', 'love', 'u']

You can get a quick overview of all three methods in the following interactive Python shell. If you’re short on time—method 1 using slice assignment is the most Pythonic solution!

Exercise: Modify the code so that only elements with start index 2 and end index 4 (included) are replaced by the joined string!

Method 1: Slice Assignment

Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. Select the slice you want to replace on the left and the values to replace it on the right side of the equation.

Here’s how you can join and replace all strings in a list slice (between indices 1 and 5) in a single line of Python code:

# Method 1: Slice Assignments
lst = ['i', 'l', 'o', 'v', 'e', 'u']
lst[1:5] = [''.join(lst[1:5])]
# ['i', 'love', 'u']

The one-liner lst[1:5] = [''.join(lst[1:5])] performs the following steps:

  • Select the slice to be replaced on the left-hand side of the equation with lst[1:5]. Read more about slicing on my Finxter blog tutorial.
  • Create a list that replaces this slice on the right-hand side of the equation with [...].
  • Select the slice of string elements to be joined together ('l', 'o', 'v', 'e') with lst[1:5].
  • Pass this slice into the join function to create a new string with all four characters 'love'.
  • This string replaces all four selected positions in the original list.

If you love the power of Python one-liners, check out my new book with the same name “Python One-Liners” on Amazon (published in 2020 with San Francisco’s high-quality NoStarch publishing house).

Method 2: List Concatenation + Slicing + Join

A simpler but quite readable method is to use simple list concatenation. Read more on my Finxter blog tutorial to master all different ways to concatenate lists in Python.

# Method 2: List Concatenation + Join
lst = ['i', 'l', 'o', 'v', 'e', 'u']
lst = lst[:1] + [''.join(lst[1:5])] + lst[5:]
# ['i', 'love', 'u']

This approach uses three slicing calls to select (or create) three lists. Then, it glues them together using the + operator. This approach has the slight disadvantage that a new list is created in memory (rather than working on the old list). Thus, it’s slightly less memory-friendly as the first method.

Method 3: Naive

This method is what a non-Python coder (maybe coming from Java or C++) would use. It’s NOT the recommended way though.

# Method 3: Naive
lst = ['i', 'l', 'o', 'v', 'e', 'u']
new = ''
for i in range(1,5):
    new += lst[i]
lst = lst[:1] + [new] + lst[5:]
# ['i', 'love', 'u']

Instead of selecting the slice of strings to be joined using slicing, the coder creates a string variable new and adds one character at-a-time. This is very inefficient as many different strings are created—each time one adds one more character to the string.

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!