How To Convert Nested List To List In Python

When working with lists in Python, you might sometimes encounter nested lists, which are lists containing other lists. In this tutorial, we will go through some simple steps on how to convert a nested list to a flat list in Python.

Step 1: Create a nested list

First, let’s create a nested list to work with. A nested list is simply a list containing other lists as its elements. Below is an example of a nested list:

This list contains three sub-lists, each with three integer elements.

Step 2: Using a list comprehension

One of the easiest ways to convert a nested list into a single, flat list is by using a list comprehension. It allows us to flatten the nested list with just a single line of code. See the example below:

In this case, we iterate through each sublist in the nested_list and then through each item in the sublist. The final flat_list will contain all the individual items from the nested_list.

Step 3: Print the result

Now that we have successfully created our flat list, let’s print it out to see the result:

The output should be:

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

Step 4: Using a function (Optional)

If you frequently work with nested lists and need to convert them into flat lists, you can create a function to achieve this. In this step, we will create a function named flatten_list that will take a nested list as input and return a flattened list using list comprehension.

Now you can use this function to convert any nested list to a flat list by simply passing the nested list as an argument:

The output will be the same as before:

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

Full code

Here’s the full code from our example above:

Conclusion

In this tutorial, we have demonstrated how to convert a nested list to a flat list using list comprehension and a function. This technique can be especially useful when you are working with complex data structures in Python.