5 Best Ways to Convert a Python List of Lists to a List of Strings

πŸ’‘ Problem Formulation: When working with data in Python, it’s common to encounter a list of lists. At times, you may need to convert this complex, nested data structure into a list of strings for easier manipulation or output generation. For instance, converting [['a', 'b'], ['c', 'd']] to ['ab', 'cd'] is one such conversion that could be required.

Method 1: Using List Comprehension

This method employs list comprehension, a concise and readable way to create lists in Python, allowing for iteration and condition checks within a single line of code. It can concatenate items in each sublist to form a string and then return a new list containing these strings.

Here’s an example:

lst_of_lsts = [['hello', 'world'], ['list', 'of', 'lists'], ['python']]
lst_of_strs = [''.join(sublst) for sublst in lst_of_lsts]
print(lst_of_strs)

Output:

['helloworld', 'listoflists', 'python']

In this snippet, the list comprehension iterates over each sublist in lst_of_lsts, joining all its elements into a single string using the string join() method, then collects these strings into lst_of_strs.

Method 2: Using the map() Function

The map() function applies a given function to every item of an iterable and returns a list of the results. In this context, it can be used with join() to convert sublists to strings.

Here’s an example:

lst_of_lsts = [['data', 'science'], ['machine', 'learning']]
lst_of_strs = list(map(''.join, lst_of_lsts))
print(lst_of_strs)

Output:

['datascience', 'machinelearning']

This code uses map() to apply the join() function to each item in lst_of_lsts. It effectively operates the same as the list comprehension, but is arguably more functional in style.

Method 3: Using a For Loop

A for loop offers a straightforward, albeit more verbose, approach to iterate over each sublist and create strings from their elements. It’s beginner-friendly and is very explicit in its operations.

Here’s an example:

lst_of_lsts = [['cat'], ['dog', 'bark'], ['fish', 'swim']]
lst_of_strs = []
for sublst in lst_of_lsts:
    lst_of_strs.append(''.join(sublst))
print(lst_of_strs)

Output:

['cat', 'dogbark', 'fishswim']

The code initializes an empty list, lst_of_strs, and appends the result of joining each sublist from lst_of_lsts as a string.

Method 4: Using itertools.chain()

If the goal is to flatten a list of lists and then create strings by concatenating certain groups together, itertools.chain() can be extremely useful. It flattens one level of nesting in the list.

Here’s an example:

from itertools import chain
lst_of_lsts = [['jump', 'high'], ['run', 'fast']]
# Flatten the list of lists into one list
flattened = list(chain.from_iterable(lst_of_lsts))
# Pairwise concatenation of the flattened list (assuming pairs)
lst_of_strs = [flattened[i] + flattened[i + 1] for i in range(0, len(flattened), 2)]
print(lst_of_strs)

Output:

['jumphigh', 'runfast']

The snippet first flattens lst_of_lsts with itertools.chain.from_iterable() and then creates a new list, lst_of_strs, by pairing and joining elements together.

Bonus One-Liner Method 5: Using a Lambda Function and map()

A lambda function provides a quick way to write small anonymous functions in Python. Used in conjunction with map(), it can efficiently convert a list of lists to list of strings.

Here’s an example:

lst_of_lsts = [['x', 'y'], ['z']]
lst_of_strs = map(lambda x: ''.join(x), lst_of_lsts)
print(list(lst_of_strs))

Output:

['xy', 'z']

The code maps an anonymous function (lambda) that joins elements of each sublist to form a string across lst_of_lsts, resulting in a map object that is then converted to a list of strings.

Summary/Discussion

  • Method 1: List Comprehension. This is clean and Pythonic. Strengths include readability and speed. Weakness might be less familiar to beginners.
  • Method 2: map() Function. Offers a functional approach, which some may prefer for its elegance. Strengths lie in its conciseness, while its weaknesses are in the potential lack of clarity for those not familiar with functional programming.
  • Method 3: Using a For Loop. It’s the most basic method, good for learners. Its strengths are in its explicitness and readability for beginners, while its weakness is that it’s more verbose than other methods.
  • Method 4: itertools.chain(). Good for more complex list flattening before transformation. Its strength is in handling more complex nestings flexibly, but it requires an understanding of iterators and may be overkill for simple cases.
  • Method 5: Lambda Function and map(). It’s a succinct one-liner. It is elegant for those who understand lambda functions but may be obscure to beginners.