How do you join a list of objects in python?

In Python, I can do:

>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'

Is there any easy way to do the same when I have a list of objects?

>>> class Obj:
...     def __str__(self):
...         return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: sequence item 0: expected string, instance found

Or do I have to resort to a for loop?

asked Jan 31, 2009 at 0:06

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

answered Jan 31, 2009 at 0:10

Adam RosenfieldAdam Rosenfield

379k96 gold badges507 silver badges584 bronze badges

6

The built-in string constructor will automatically call obj.__str__:

''.join(map(str,list))

answered Jan 31, 2009 at 0:16

Kenan BanksKenan Banks

201k34 gold badges151 silver badges171 bronze badges

8

I know this is a super old post, but I think what is missed is overriding __repr__, so that __repr__ = __str__, which is the accepted answer of this question marked duplicate.

answered Nov 21, 2018 at 4:54

NotAnAmbiTurnerNotAnAmbiTurner

2,2651 gold badge20 silver badges42 bronze badges

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.

answered Aug 15, 2018 at 11:41

1

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.

0124

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
  • Method 2: Join + Generator Expression + Str
  • Method 3: Join + Generator Expression + Custom String Representation
  • Method 4: Join + Map + Lambda
  • Method 5: Join + Map + Str
  • Method 6: Simple Loop + Str (Naive)
  • Where to Go From Here?

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.

How do you join a list of objects in python?

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 : . 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)
print(s)
# 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!

How do you join a list of objects in python?

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.

How do you combine lists of objects in python?

Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How do you join list objects?

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.

How do you join a list in python?

One of the easiest ways are by using the + operator..
Join two list: list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2. ... .
Append list2 into list1: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] for x in list2: ... .
Use the extend() method to add list2 at the end of list1: list1 = ["a", "b" , "c"] list2 = [1, 2, 3].

Can we join list in python?

We can use python string join() function to join a list of strings. This function takes iterable as argument and List is an interable, so we can use it with List.