To join specific list elements (e.g., with indices
4) and return the joined string that’s the concatenation of all those, use the expression
''.join([lst[i] for i in [0, 2, 4]]). The list comprehension statement creates a list consisting of elements
''.join() method concatenates those elements using the empty string as a delimiter.
Today, I stumbled upon the following problem—and I found it quite interesting and of high educational value.
Problem: Given a list of strings. How to join specific list elements and return the joined string that’s the concatenation of all those specific list elements?
Example: You’ve got the following list of strings.
lst = ['hello ', 'bye', 'world', '?', '!']
You want to join and concatenate the first, third, and fourth elements of the list.
Related article: A variant of this problem is to join all element in a slice and replace the slice with the joined string. Read about this solution on my blog article.
Here’s a quick overview of the methods, I’m going to discuss in this tutorial:
Exercise: Concatenate elements with indices 1, 2, and 3 with each of the methods!
Method 1: Indexing + Concatenation
lst = ['hello ', 'bye', 'world', '?', '!'] print(lst + lst + lst) # hello world!
However, if there’s a regularity in your indices in that you want to concatenate every i-th element in your list, you can use slicing.
Method 2: Slicing + Join
You’ll use two concepts in this method:
- Slicing to select the string elements you want to concatenate.
string.join(...)method to concatenate the elements in the slice.
Slicing is a concept to carve out a substring from a given string. Use slicing notation
s[start:stop:step] to access every
step-th element starting from index
start (included) and ending in index
stop (excluded). All three arguments are optional, so you can skip them to use the default values (
step=1). For example, the expression
s[2:4] from string
'hello' carves out the slice
'll' and the expression
s[:3:2] carves out the slice
string.join(iterable) method joins the string elements in the
iterable to a new string by using the
string on which it is called as a delimiter.
lst = ['hello ', 'bye', 'world', '?', '!'] print(''.join(lst[::2])) # hello world!
This method is more effective because it doesn’t involve concatenating multiple immutable data types (string). This avoids the creation of multiple strings in memory. Also, it’s more concise—even if you want to concatenate large sublists.
Method 3: Itemgetter + Join
If there’s no index pattern of elements you want to concatenate, you cannot use slicing. In this case, it’s best to access arbitrary elements from your list. You can use the
from operator import itemgetter lst = ['hello ', 'bye', 'world', '?', '!'] print(''.join(itemgetter(0, 2, 4)(lst))) # hello world!
itemgetter returns a function that returns the elements with
4 from the list (or, more general, iterable) you pass into the function.
Method 4: List Comprehension + Join
To create a manual list with only elements 0, 2, and 4, you can also use a short list comprehension call.
lst = ['hello ', 'bye', 'world', '?', '!'] print(''.join([lst[i] for i in [0, 2, 4]])) # hello world!
lst = ['hello ', 'bye', 'world', '?', '!'] print(''.join(lst[i] for i in [0, 2, 4])) # hello world!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.