
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to flatten a shallow list in Python?
A simple and straightforward solution is to append items from sublists in a flat list using two nested for loops.
lst = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] flatlist = [] for sublist in lst: for item in sublist: flatlist.append(item) print (flatlist)
A more compact and Pythonic solution is to use chain() function from itertools module.
>>> lst =[[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] >>> import itertools >>> flatlist = list(itertools.chain(*lst)) >>> flatlist [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
- Related Articles
- Python - Ways to flatten a 2D list
- Flatten Tuples List to String in Python
- Python program to Flatten Nested List to Tuple List
- Flatten Nested List Iterator in Python
- Flatten tuple of List to tuple in Python
- Python Program to Flatten a Nested List using Recursion
- Python Program to Flatten a List without using Recursion
- Flatten given list of dictionaries in Python
- How to flatten a list using LINQ C#?
- How to Flatten a Matrix using numpy in Python?
- Flatten a multilevel linked list in C++
- How do you make a shallow copy of a list in Java?
- Flatten Binary Tree to Linked List in C++
- How to flatten a Docker image?
- How to create a shallow copy of Hashtable in C#?

Advertisements