How to Use Python’s Join() on a List of Objects (Not Strings)?

5/5 - (1 vote)

The most Pythonic way to concatenate a list of objects is the expression ''.join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter. The result is a single string value that’s the concatenation of the objects’ string representations.

What's The Most Pythonic Way to Concatenate a List of Objects into a String?

Writing Pythonic code is at the heart of being an effective coder—and if you choose the wrong ways of solving a problem, you’ll open yourself up for criticism and struggles throughout your programming career. So, what’s the most Pythonic way of solving the following problem?

Problem: Given a list of objects. How to concatenate the string representations of those objects?

Example: You have the following list of objects.

class Obj:
    def __init__(self, val):
        self.val = val

    def __str__(self):
        return str(self.val)

lst = [Obj(0), Obj(1), Obj(2), Obj(4)]

You want to obtain the following result of concatenated string representations of the objects in the list.


Want to play? Run the following interactive code shell:

Exercise: Run the interactive code snippet. Which method do you like most?

Method 1: Join + List Comprehension + Str

This method uses three Python features.

First, the string.join(iterable) method expects an iterable of strings as input and concatenates those using the string delimiter. You can read more about the join() function in our ultimate blog guide.

Second, list comprehension is the Pythonic way to create Python lists in a single line. You use the syntax [expression + statement].

  • In the expression, you define how each element should be modified before adding it into a new list.
  • In the statement, you define which elements to modify and add to the list in the first place.

You can read more about list comprehension in the detailed Finxter guide on the topic.

Third, the str(...) function converts any Python object into a string representation. If you define your custom objects, you should overwrite the __str__() method to customize how exactly your objects are represented as strings.

Combining those three features results in the following simple solution to concatenate the string representations of a list of objects.

print(''.join([str(x) for x in lst]))
# 0124

But there’s a slight simplification lurking around. Read on to learn which!

Method 2: Join + Generator Expression + Str

The previous method has shown a quite effective way to concatenate the string representations of some objects using the join() function of Python strings. As the join() function expects a list of strings, you need to convert all objects x into plain strings using the str(x) function.

Concatenate string representations of list of objects with join() function and generator expression.

However, there’s no need to create a separate list in which you store the string representations. Converting one object at a time is enough because the join function needs only an iterable as an input—and not necessarily a Python list. (All Python lists are iterables but not all iterables are Python lists.)

To free up the memory, you can use a generator expression (without the square brackets needed to create a list):

print(''.join(str(x) for x in lst))
# 0124

In contrast to Method 1, this ensures that the original list does not exist in memory twice—once as a list of objects and once as a list of string represenations of those exact objects. Therefore, this method can be considered the most Pythonic one.

Method 3: Join + Generator Expression + Custom String Representation

A slight modification of the previous version is to use your own custom string representation—rather than the one implemented by the __str__ method.

print(''.join(str(x.val) for x in lst))
# 0124

This gives you some flexibility how you can represent each object for your specific application.

Method 4: Join + Map + Lambda

The map() function transforms each tuple into a string value, and the join() method transforms the collection of strings to a single string—using the given delimiter '--'. If you forget to transform each tuple into a string with the map() function, you’ll get a TypeError because the join() method expects a collection of strings.

Lambda functions are anonymous functions that are not defined in the namespace (they have no names). The syntax is: lambda <argument name(s)> : <return expression>. You’ll see an example next, where each function argument is mapped to its string representation.

print(''.join(map(lambda x: str(x), lst)))
# 0124

This method is a more functional programming style—and some Python coders prefer that. However, Python’s creator Guido van Rossum preferred list comprehension over functional programming because of the readability. That’s why Methods 1-3 should be preferred in general.

If you absolutely want to take functional programming, use the next version:

Method 5: Join + Map + Str

There’s no need to use the lambda function to transform each list element to a string representation—if there’s a built-in function that’s already doing exactly this: the str(...) function you’ve already seen!

print(''.join(map(str, lst)))
# 0124

Because of its conciseness and elegance, passing the str function name as a function argument into the map function is the most Pythonic functional way of solving this problem.

Method 6: Simple Loop + Str (Naive)

Sure, you can also solve the problem in a non-Pythonic way by using a simple for loop and build up the string:

s = ''
for x in lst:
    s += str(x)
# 0124

But that’s not only less concise, it’s also less efficient. So, a master coder in Python would never use such a method!

If you want to become a Python master coder, check out my free in-depth Python email course. Join tens of thousands of ambitious Python coders and become a Python master the automatic way!

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!