Python Join List [Ultimate Guide]

The string.join(iterable) method concatenates all the string elements in the iterable (such as a list, string, or tuple) and returns the result as a new string. The string on which you call it is the delimiter string—and it separates the individual elements. For example, '-'.join(['hello', 'world']) returns the joined string 'hello-world'.

>>> '-'.join(['hello', 'world'])
'hello-world'

In this ultimate guide, you’ll learn everything you need to know about joining list elements in Python.

To give you a quick overview, let’s have a look at the following problem.

Problem: Given a list of elements. How to join the elements by concatenating all elements in the list?

Example: You want to convert list ['learn ', 'python ', 'fast'] to the string 'learn python fast'.

Quick Solution: to convert a list of strings to a string, do the following.

  • Call the ''.join(list) method on the empty string '' that glues together all strings in the list and returns a new string.
  • The string on which you call the join method is used as a delimiter between the list elements.
  • If you don’t need a delimiter, just use the empty string ''.

Code: Let’s have a look at the code.

lst = ['learn ', 'python ', 'fast']
print(''.join(lst))

The output is:

learn python fast

Exercise: Try it yourself in our interactive Python shell and change the delimiter string!

You can also use another delimiter string, for example, the comma:

lst = ['learn' , 'python', 'fast']
print(','.join(lst))
# learn,python,fast

Definition: Python Join List With Delimiter

The 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.

Here’s a short example:

friends = ['Alice', 'Bob', 'Carl']

# Empty delimiter string ''
print(''.join(friends))
# AliceBobCarl

# Delimiter string 'xxx'
print('xxx'.join(friends))
# AlicexxxBobxxxCarl

The string elements in the list friends are concatenated using the delimiter string '' in the first example and 'xxx' in the second example.

Related articles:

Syntax

You can call this method on each list object in Python. Here’s the syntax:

string.join(iterable)

ArgumentDescription
iterableThe elements to be concatenated.
Concatenate string representations of list of objects with join() function and generator expression.

Python Join List of Strings With Comma

Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a comma as the delimiter between the list elements?

Example: You want to convert list ['learn', 'python', 'fast'] to the string 'learn,python,fast'.

Solution: to convert a list of strings to a string, call the ','.join(list) method on the delimiter string ',' that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print(','.join(lst))

The output is:

learn,python,fast

Python Join List of Strings With Newline

Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a newline character as the delimiter between the list elements?

Example: You want to convert list ['learn', 'python', 'fast'] to the string 'learn\npython\nfast' or as a multiline string:

'''learn
python
fast'''

Solution: to convert a list of strings to a string, call the '\n'.join(list) method on the newline character '\n' that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print('\n'.join(lst))

The output is:

learn
python
fast

Python Join List of Strings With Space

Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a space as the delimiter between the list elements?

Example: You want to convert list ['learn', 'python', 'fast'] to the string 'learn python fast'. (Note the empty spaces between the terms.)

Solution: to convert a list of strings to a string, call the ' '.join(list) method on the string ' ' (space character) that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print(' '.join(lst))

The output is:

learn python fast

Python Join List With Single and Double Quotes

Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a comma character followed by an empty space as the delimiter between the list elements? Additionally, you want to wrap each string in double quotes.

Example: You want to convert list ['learn', 'python', 'fast'] to the string '"learn", "python", "fast"' :

Solution: to convert a list of strings to a string, call the ', '.join('"' + x + '"' for x in lst) method on the delimiter string ', ' that glues together all strings in the list and returns a new string. You use a generator expression to modify each element of the original element so that it is enclosed by the double quote " chararacter.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print(', '.join('"' + x + '"' for x in lst))

The output is:

"learn", "python", "fast"

Python Join List with Underscore

The 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.

The '_'.join(list) method on the underscore string '_' glues together all strings in the list using the underscore string as a delimiter—and returns a new string.

For example, the expression '_'.join(['a', 'b', 'c']) returns the new string 'a_b_c'. Here’s another example:

friends = ['Alice', 'Bob', 'Carl']
print('_'.join(friends))
# Alice_Bob_Carl

The string elements in the list friends are concatenated using the underscore character '_' as a delimiter string.

Python Join List With Carriage Return / Newline

Do you want to join all string elements by using a carriage return '\n' (also called newline character) as a delimiter?

Use the newline character '\n' as a string value on which you call the '\n'.join(iterable) method to join the string elements in the iterable to a new string with new-line-separated elements.

Here’s a minimal example:

friends = ['Alice', 'Bob', 'Carl']
print('\n'.join(friends))

You concatenate all string elements by using the newline character as a delimiter producing the output:

Alice
Bob
Carl

Python Join List With Tabs

Do you want to join all string elements by using a tabular character '\t' as a delimiter?

Use the tabular character '\t' as a string value on which you call the '\t'.join(iterable) method to join the string elements in the iterable to a new string with tabular-separated elements.

Here’s a minimal example:

friends = ['Alice', 'Bob', 'Carl']
print('\t'.join(friends))

You concatenate all string elements by using the newline character as a delimiter producing the output:

Alice	Bob	Carl

Python Join List With None

Say, your goal is to concatenate an iterable of strings and, possibly, None elements with a separator string?

For example, you may have tried '-'.join(['Alice', 'Bob', None, None, 'Frank']) but Python throws a TypeError expecting only string elements:

>>> '-'.join(['Alice', 'Bob', None, None, 'Frank'])
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    '-'.join(['Alice', 'Bob', None, None, 'Frank'])
TypeError: sequence item 2: expected str instance, NoneType found

The solution is simple: filter the list to make sure that all remaining elements are strings. There are many ways to filter a list (feel free to read my ultimate guide on filtering lists)—but the most Pythonic is list comprehension (or generator expressions if you don’t need to create a list and an iterable is fine):

>>> lst = ['Alice', 'Bob', None, None, 'Frank']
>>> '-'.join(x for x in lst if type(x) == str)
'Alice-Bob-Frank'

The generator expression x for x in lst if type(x) == str creates an iterable of elements that are in the lst and are also of type string. This is how you can handle lists of strings that also contain None elements.

Python Join List of Integers

Problem: You want to convert a list into a string but the list contains integer values.

Example: Convert the list [1, 2, 3] to a string '123'.

Solution: Use the join method in combination with a generator expression to convert the list of integers to a single string value:

lst = [1, 2, 3]
print(''.join(str(x) for x in lst))
# 123

The generator expression converts each element in the list to a string. You can then combine the string elements using the join method of the string object.

If you miss the conversion from integer to string, you get the following TypeError:

lst = [1, 2, 3]
print(''.join(lst))

'''
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 2, in <module>
    print(''.join(lst))
TypeError: sequence item 0: expected str instance, int found
'''

Python Join List of Floats

Problem: You want to convert a list into a string but the list contains float values.

Example: Convert the list [1.0, 2.0, 3.0] to a string '1.0+2.0+3.0'.

Solution: Use the join method in combination with a generator expression to convert the list of integers to a single string value:

lst = [1.0, 2.0, 3.0]
print('+'.join(str(x) for x in lst))
# 1.0+2.0+3.0

The generator expression converts each float in the list to a string. You can then combine the string elements using the join method of the string object.

Python Join List of Booleans

Problem: Given a list of Boolean elements. What’s the best way to join all elements using the logical OR or logical AND operations?

Example: Convert the list [True, True, False] using the logical “and” operation to True and True and False = False or using the logical “or” operation to True or True or False = True.

Solution: Use the built-in Python function all() to perform logical “AND” and any() to perform logical “OR”.

lst = [True, True, False]

# Logical "AND"
print(all(lst))
# False

# Logical "OR"
print(any(lst))
# True

This way, you can combine an arbitrary iterable of Booleans into a single Boolean value.

Python Join List of Tuples

Say, you’ve got a list of tuples and you want to convert it to a string (see this article for a detailed tutorial). The easiest way to accomplish this is to use the default string conversion method with str(...).

>>> lst = [(1,1), (2,1), (4,2)]
>>> str(lst)
'[(1, 1), (2, 1), (4, 2)]'

The result is a nicely formatted string representation of your list of tuples.

However, if you want to customize the delimiter string, you can use the join() method in combination with the map() function:

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

print('--'.join(map(str, lst)))
# (1, 1)--(2, 1)--(4, 2)

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.

If you want to flatten the list and integrate all tuple elements into a single large collection of elements, you can use a simple list comprehension statement [str(x) for t in lst for x in t].

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

print('\n'.join([str(x) for t in lst for x in t]))
'''
1
1
2
1
4
2
'''

If you want to redefine how to print each tuple—for example, separating all tuple values by a single whitespace character—use the following method based on a combination of the join() method and the map() function with a custom lambda function lambda x: str(x[0]) + ' ' + str(x[1]) to be applied to each list element.

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

print('\n'.join(map(lambda x: str(x[0]) + ' ' + str(x[1]), lst)))
'''
1 1
2 1
4 2
'''

Python Join List of Sets

Problem: Given a list or a collection of sets. How to join those sets using the union operation?

Example: You’ve got a list of sets [{1, 2, 3}, {1, 4}, {2, 3, 5}] and you want to calculate the union {1, 2, 3, 4, 5}.

Solution: To union a list of sets, use the following strategy:

  • Create a new set using the set() constructor.
  • Call the union() method on the new set object.
  • Pass all sets as arguments into the union() method by unpacking the list with the asterisk operator *list.
  • The result of the union() method is a new set containing all elements that are in at least one of the sets.

Code: Here’s the one-liner code that unions a collection of sets.

# Create the list of sets
lst = [{1, 2, 3}, {1, 4}, {2, 3, 5}]

# One-Liner to union a list of sets
print(set().union(*lst))

The output of this code is the union of the three sets {1, 2, 3}, {1, 4}, {2, 3, 5}:

{1, 2, 3, 4, 5}

If you love Python one-liners, check out my new book “Python One-Liners” (Amazon Link) that teaches you a thorough understanding of all single lines of Python code.

Related articles:

Python Join List of Bytes

Python Bytes are similar than Python strings (at least for you, the person who used the Byte data structure in their program).

So, joining a list of Bytes is similar than joining a list of strings: use the join method! The Byte object comes with a method Byte.join(iterable) that concatenates all Byte objects in the iterable.

Keep in mind that a Byte object is a sequence of bytes by itself (and not a sequence of bits as you may have expected).

Syntax: Byte.join(iterable)

ArgumentDescription
iterableA collection of Byte objects.

Examples: Let’s see a bunch of examples on how you can join a collection of Byte objects!

lst = [b'Python', b'is', b'beautiful']

# Example 1
print(b' '.join(lst))
b'Python is beautiful'

# Example 2
print(b'-'.join(lst))
b'Python-is-beautiful'

# Example 3
print(b'\n'.join(lst))
b'Python\nis\nbeautiful'

You get the point: you call the join() method on the Byte object and pass an iterable of Byte objects to be concatenated. Notice how all involved data types are Byte objects!

Read more in my article: Python Join List of Bytes (and What’s a Python Byte Anyway?)

Python Join List of Dictionaries

Problem: Say, you’ve got a list of dictionaries:

[{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}]

Notice how the first and the last dictionaries carry the same key 'a'.

How do you merge all those dictionaries into a single dictionary to obtain the following one?

{'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

Notice how the value of the duplicate key 'a' is the value of the last and not the first dict in the list of dicts.

Solution: You can use dictionary comprehension {k:v for x in l for k,v in x.items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.

  • Create a new dictionary using the {...} notation.
  • Go over all dictionaries in the list of dictionaries l by using the outer loop for x in l.
  • Go over all (key, value) pairs in the current dictionary x by using the x.items() method that returns an iterable of (key, value) pairs.
  • Fill the new dictionary with (key, value) pairs k:v using the general dictionary comprehension syntax {k:v for ...}.
l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}]

d = {k:v for x in l for k,v in x.items()}
print(d)
# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

This is the most Pythonic way to merge multiple dictionaries into a single one and it works for an arbitrary number of dictionaries.

Python Join List Except First or Last Element

How do you join all strings in a list—except the first (or last) element?

Use the slicing operation lst[1:] to retrieve all but the first and lst[:-1] to retrieve all but the last elements from the list. Then, call the join() function on the resulting slice.

Here’s the code:

lst = ['Alice', 'Bob', 'Liz']

# Join except first element
joined = ' + '.join(lst[1:])
print(joined)
# Bob + Liz

# Join except last element
joined = ' + '.join(lst[:-1])
print(joined)
# Alice + Bob

This way, you can join all list elements, except the first or last elements.

Python Join List Remove Duplicates

Problem: Given two lists [1, 2, 2, 4] and [2, 5, 5, 5, 6]. How do you combine those lists to the new list [1, 2, 2, 4, 5, 6] by removing the duplicates in the second list?

Note: You want to remove all duplicates in the second list and the elements in the second list that are already in the first list.

Solution: Use the following three steps to combine two lists and remove the duplicates in the second list:

  • Convert the first and second lists to a set using the set(...) constructor.
  • Use the set minus operation to get all elements that are in the second list but not in the first list.
  • Create a new list by concatenating those elements to the first list.

Here’s the code:

# Create the two lists
l1 = [1, 2, 2, 4]
l2 = [2, 5, 5, 5, 6]

# Find elements that are in second but not in first
new = set(l2) - set(l1)

# Create the new list using list concatenation
l = l1 + list(new)
print(l)
# [1, 2, 2, 4, 5, 6]

Related articles:

Python Join List Reverse

Problem: Given a list of strings. How to join the strings in reverse order?

Example: You want to join the following list

l = ['n', 'o', 'h', 't', 'y', 'p']

to obtain the joined string in reverse order

python

Let’s get a short overview on how to accomplish this.

Solution: The most Pythonic method to reverse and join a list of strings is to use slicing with a negative step size.

You can slice any list in Python using the notation list[start:stop:step] to create a sublist starting with index start, ending right before index stop, and using the given step size—which can also be negative to slice from right to left. If you need a refresher on slicing, check out our detailed Finxter blog tutorial or our focused book “Coffee Break Python Slicing”.

Here’s the first method to reverse a list of strings and join the elements together:

l = ['n', 'o', 'h', 't', 'y', 'p']


# Method 1
print(''.join(l[::-1]))
# python

Related articles:

Python Join List Range

Problem: Given a range object—which is an iterable of integers—how to join all integers into a new string variable?

Example: You have the following range object:

range(10)

You want the following string:

'0123456789'

Solution: To convert a range object to a string, use the string.join() method and pass the generator expression str(x) for x in range(...) to convert each integer to a string value first. This is necessary as the join function expects an iterable of strings and not integers. If you miss this second step, Python will throw a TypeError:

print(''.join(range(10)))
'''
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 2, in <module>
    print(''.join(range(10)))
TypeError: sequence item 0: expected str instance, int found
'''

So, the correct way is to convert each element to a string using the generator expression str(x) for x in range(...) inside the join(...) argument list. Here’s the correct code that joins together all integers in a range object in the most Pyhtonic way:

print(''.join(str(x) for x in range(10)))
'0123456789'

You can use different delimiter strings if you need to:

print('-'.join(str(x) for x in range(10)))
'0-1-2-3-4-5-6-7-8-9'

Related articles:

Python Join List By Row / Column

Problem: Given a number of lists l1, l2, …, ln. How to merge them into a list of tuples (column-wise)?

Example: Say, you want to merge the following lists

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99]

into a list of tuples by grouping the columns:

[(0, 1, 2), 
 ('Alice', 'Bob', 'Liz'), 
 (4500.0, 6666.66, 9999.99)]

Solution: The most Pythonic way that merges multiple lists into a list of tuples is the zip function. It accomplishes this in a single line of code—while being readable, concise, and efficient.

The zip() function takes one or more iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

Here’s the code solution:

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99]

print(list(zip(l0, l1, l2)))

The output is the following list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

Note that the return value of the zip() function is a zip object. You need to convert it to a list using the list(...) constructor to create a list of tuples.

If you have stored the input lists in a single list of lists, the following method is best for you!

You can use the asterisk operator *lst to unpack all inner elements from a given list lst. Especially if you want to merge many different lists, this can significantly reduce the length of your code. Instead of writing zip(lst[0], lst[1], ..., lst[n]), simplify to zip(*lst) to unpack all inner lists into the zip function and accomplish the same thing!

lst = [[0, 'Alice', 4500.00],
       [1, 'Bob', 6666.66],
       [2, 'Liz', 9999.99]]
print(list(zip(*lst)))

This generates the list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

I’d consider using the zip() function with unpacking the most Pythonic way to merge multiple lists into a list of tuples.

Python Join List of Unicode Strings

This morning—when reading a WhatsApp message during my coffee break ☕— I wondered: what about the Python unicode support? Can you process special Unicode characters such as ⭐ and ? within normal strings? As it turns out, you can! But not with all tools (many of them are still legacy). Read on to learn more about the state of Unicode support in Python! ?

Problem: Given a Python list of unicode strings. How to join all list element to a single string?

Example: Say, you have the following unicode Python list:

a = [u'⭐', u'?', u'?', u'?‍?', u'?', u'❤']

Note that in Python 3+, all strings are already UTF-8 encoded—which means that they are Unicode per default! That’s why the following statement without the 'u' prefix does the same thing as the previous statement:

a = ['⭐', '?', '?', '?‍?', '?', '❤']

Your goal is to join the elements with a delimiter, say ' ? ' to generate the following output:

⭐   ?   ?   ?   ?   ?   ?‍?   ?   ?   ?   ❤

Solution: The method is theoretically simple—you use the string.join(list) method to join the list of unicode strings.

a = ['⭐', '?', '?', '?‍?', '?', '❤']
print('   ?   '.join(a))

This generates the output:

⭐   ?   ?   ?   ?   ?   ?‍?   ?   ?   ?   ❤

Unfortunately, many Python editors cannot handle it (they still live in the 20th century). My IDLE code editor simply crashes if I try to copy and paste the code into it! ?

The online code editor Trinket.io complains (this is a screenshot):

However, the Repl.it code editor works! Try it yourself in your browser:

Exercise: Click “Run” and see the Unicode output—isn’t this beautiful? Try other Unicode characters (hit WindowsSymbol + . to open the Emoji table).

Python Join List in Pairs

Problem: Given a list of strings. Join the first with the second string, the second with the third, and so on.

Example: Let’s consider the following minimal example:

['x', 'y', 'v', 'w']

Is there any simple way to pair the first with the second and the third with the fourth string to obtain the following output?

['xy', 'vw']

Note that the length of the strings in the list is variable so the following would be a perfectly acceptable input:

['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff'] 

You can play with all three methods before diving into each of them:

Exercise: What’s the most Pythonic method?

Read more about this topic in my detailed blog tutorial!

Python Join List as Path

Do you want to join a list of strings to a path in your specific operating system? Remembering the correct path separator can be a real pain. Fortunately, the os.path.join() method comes to the rescue!

The os.path.join() method takes one or more path arguments and returns a concatenation of the path arguments with the correct directory separator in your operating system. If you want to join a list of paths, you need to unpack the list into the argument list. For example, os.path.join(*lst) would join the list ['c:', 'your', 'directory'] into the path string 'c://your/directory' in a Windows environment.

Syntax: os.path.join(path, *paths)

Description: Join one or more path components in path and *paths. Concatenates path components using the directory separator string stored in os.sep. If a component is an absolute path such as 'c:\user\path' or a drive letter such as 'c:', all previous path components are thrown away and joining continues from the absolute path component. (improved from docs)

Python | Join List as Path

Examples: Let’s dive into a minimal example how you can join the path stored in a Python list.

import os
p = ['c:', 'user', 'path', 'file.py']
print(os.path.join(*p))

The output is the joined path:

'c:user\path\file.py'

The code performs the following steps:

You can read more details about joining a list of path strings in my new Finxter blog tutorial.

Python Join List Slice

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!

Solution: 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])]
print(lst)
# ['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).

Read more about this topic here.

Python Join Specific List Elements

To join specific list elements (e.g., with indices 0, 2, and 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 lst[0], lst[2], and lst[4]. The ''.join() method concatenates those elements using the empty string as a delimiter.

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.

'hello world!'
How to Join Specific List Elements in Python?

Here’s a quick overview of the methods:

Exercise: Concatenate elements with indices 1, 2, and 3 with each of the methods!

Related articles:

Python Join List of DataFrames

To join a list of DataFrames, say dfs, use the pandas.concat(dfs) function that merges an arbitrary number of DataFrames to a single one.

When browsing StackOverflow, I recently stumbled upon the following interesting problem. By thinking about solutions to those small data science problems, you can improve your data science skills, so let’s dive into the problem description.

Problem: Given a list of Pandas DataFrames. How to merge them into a single DataFrame?

Example: You have the list of Pandas DataFrames:

df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]})

# List of DataFrames
dfs = [df1, df2, df3]

Say, you want to get the following DataFrame:

       Alice      Bob
0         18       24
1  scientist  student
2      24000    12000
0         19       25
1  scientist  student
2      25000    11000
0         20       26
1  scientist  student
2      26000    10000

You can try the solution quickly in our interactive Python shell:

Exercise: Print the resulting DataFrame. Run the code. Which merging strategy is used?

Read about the solution of this exercise here.

Python Join List Comprehension and Map

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

Solution with List Comprehension / Generator Expression:

The join() function expects a list of strings. So, 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

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.

Alternative Solution with Map:

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.

Optimization: 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.

Python Join List of Lists

When browsing StackOverflow, I stumble upon this question from time to time: “How to Join a List of Lists?“. My first thought is that the asking person is referring to the join() function that converts an iterable (such as a list) to a string by concatenating its elements.

But nothing can be further from the truth! The question is usually about “flattening” the list: to transform a nested list of lists such as [[1, 2, 3], [4, 5, 6]] to a flat list [1, 2, 3, 4, 5, 6]. So, the real question is:

How to Flatten a List of Lists in Python?

Problem: Given a list of lists. How to flatten the list of lists by getting rid of the inner lists—and keeping their elements?

Example: You want to transform a given list into a flat list like here:

lst = [[2, 2], [4], [1, 2, 3, 4], [1, 2, 3]]

# ... Flatten the list here ...

print(lst)
# [2, 2, 4, 1, 2, 3, 4, 1, 2, 3]
Flatten a List of Lists with List Comprehension

Solution: Use a nested list comprehension statement [x for l in lst for x in l] to flatten the list.

lst = [[2, 2], [4], [1, 2, 3, 4], [1, 2, 3]]

# ... Flatten the list here ...
lst = [x for l in lst for x in l]

print(lst)
# [2, 2, 4, 1, 2, 3, 4, 1, 2, 3]

Explanation: In the nested list comprehension statement [x for l in lst for x in l], you first iterate over all lists in the list of lists (for l in lst). Then, you iterate over all elements in the current list (for x in l). This element, you just place in the outer list, unchanged, by using it in the “expression” part of the list comprehension statement [x for l in lst for x in l].

Try It Yourself: You can execute this code snippet yourself in our interactive Python shell. Just click “Run” and test the output of this code.

Exercise: How to flatten a three-dimensional list (= a list of lists of lists)? Try it in the shell!

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!