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:
1 |
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
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:
1 |
flat_list = [item for sublist in nested_list for item in sublist] |
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:
1 |
print(flat_list) |
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.
1 2 |
def flatten_list(nested_list): return [item for sublist in nested_list for item in sublist] |
Now you can use this function to convert any nested list to a flat list by simply passing the nested list as an argument:
1 2 |
flat_list = flatten_list(nested_list) print(flat_list) |
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:
1 2 3 4 5 6 |
def flatten_list(nested_list): return [item for sublist in nested_list for item in sublist] nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat_list = flatten_list(nested_list) print(flat_list) |
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.