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
If you have just a few elements, it’s best to use simple indexing in combination with string concatenation
+. You just won’t find a more readable solution:
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!
This is concise, efficient, and readable (for Python coders). You don’t even need to create a list but use a generator expression to pass into the
join() method, which may be slightly more Pythonic:
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!
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.
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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.