If you have a nested list (list of lists) in Python and you want to convert it into a single list i.e. flatten a nested list, you can try writing a recursion function.
Example 1: Using recursion function:
def flattern_nested_list(input_nested_list):
flat_list = []
for element in input_nested_list:
if isinstance(element, list):
flat_list.extend(flattern_nested_list(element)) # recursion
else:
flat_list.append(element)
return flat_list
# nested list
my_nested_list = [1,2,3,4,[5,6,7,8],[[9,10],11,12]]
# calling our custom function to get flattern list
my_flat_list = flattern_nested_list(my_nested_list)
# print the result
print(my_flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Example 2: Using List Comprehension:
my_nested_list = [
["USA", "Canada", "Mexico"],
["India", "China","Japan"],
["Australia", "Sweden", "France", "UK"]
]
flat_list = [item for sub_list in my_nested_list for item in sub_list]
print(flat_list)
Output:
['USA', 'Canada', 'Mexico', 'India', 'China', 'Japan', 'Australia', 'Sweden', 'France', 'UK']
In the above example flat_list is created using a list comprehension with nested loops. The outer loop iterates through each sub_list in the nested list, and the inner loop iterates through each item in the sub_list, appending it to the flat_list.
References:
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensionsYou can download this article in various formats for your convenience. Choose from the options below:
Facing issues? Have Questions? Post them here! I am happy to answer!
- Python List of Lists with Examples
- Fix: ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No matching distribution found for tkinter
- How to Convert Python Notebook .ipynb (JSON) to Executable .py Module
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python: Pandas Merge Indicator (Left, Right and Both) Example
- Fix: EOFError Exception in Python
- How to URL Decode a Query String in Python
- How to take user input from the console in a Python program
- Compare two lists in Python and return matches
- How to change the Python Default version
- Fix: KeyError: exception in Python
- How to get the Execution Time of A Python Program
- Fix: ModuleNotFoundError: No module named boto3 [Python]
- How to get unique values from a list in Python
- How to pip install Python Modules in VSCode
- Python: Fix - TypeError: NoneType object is not iterable
- How to delete a file using Python code example
- How to create a dictionary comprehension in Python
- Python: Get just the filename without extension using Path
- How to comment out a block of code in Python
- How to add two float numbers in Python
- Python: How to POST Json Data with HTTP Request
- Get MD5 Hash as Checksum of a String in Python
- Python - Convert float to String
- How to Parse XML String in Python
- Python: Pandas Rename Columns with List Example - Python
- How to get file path of a file using Java Code? - Java
- Quick Fix: How to Force Restart Your iPhone - iOS
- Python: Pandas Merge With Examples - Python
- Java 8 Predicate Functional Interface isEqual() Method Example - Java
- Enable Spellcheck in eclipse workspace - Eclipse
- PHP Fatal error : Call to a member function bind_param() on a non-object - PHP
- Fix: pip install mysqlclient error: subprocess-exited-with-error - MySQL