How to Collapse a List in Python

In Python, a list is a collection of items that are ordered and changeable. Lists can contain a mix of data types such as strings, integers, and even other lists. Oftentimes, you might want to collapse, or flatten, a list in Python.

This basically means you want to turn a list of lists into a single list. This method is often used when dealing with complex data structures. In this tutorial, we will discuss how to collapse a list in Python using various methods.

Method 1: Using a simple loop

A simple method to collapse a list would be to iterate over the elements using a loop. This can be done as follows:

def collapse_list(list):
    collapsed_list = []
    for sublist in list:
        for item in sublist:
            collapsed_list.append(item)
    return collapsed_list

You can test this function as follows:

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(collapse_list(nested_list))

Method 2: Using List Comprehension

A more pythonic method to collapse a list would be to use list comprehension. List comprehension is a concise way to create lists in Python:

def collapse_list(list):
    return [item for sublist in list for item in sublist]

The result will be the same as the previous method. You can test this function as well.

Method 3: Using itertools.chain()

The itertools.chain() function is another simple and elegant method for flattening a list. It is part of the itertools module, which consists of tools for handling iterators:

import itertools

def collapse_list(input_list):
    return list(itertools.chain(*input_list))

Complete Code

#Method 1
def collapse_list1(list):
    collapsed_list = []
    for sublist in list:
        for item in sublist:
            collapsed_list.append(item)
    return collapsed_list

#Method 2
def collapse_list2(list):
    return [item for sublist in list for item in sublist]

#Method 3
import itertools
def collapse_list3(input_list):
    return list(itertools.chain(*input_list))

#Testing the functions
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(collapse_list1(nested_list))
print(collapse_list2(nested_list))
print(collapse_list3(nested_list))

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In conclusion

These are some of the common methods for collapsing a list in Python. Depending on the specific requirements of your task, you might choose a simple loop or list comprehension for their simplicity if you want to stay with basic Python features. If you are dealing with complex or large data, itertools.chain() could be an efficient solution. Enjoy collapsing!