

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to join list of lists in python?
There are different ways to flatten a list of lists. Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object.
L1=[[1,2],[3,4,5],[6,7,8,9]] flat=[] for i in L1: for j in i: flat.append(j) print (flat)
Another method is to use a generator function to yield an iterator and convert it to a list
def flatten(list): for i in list: for j in i: yield j L1=[[1,2,3],[4,5],[6,7,8,9]] flat=flatten(L1) print (list(flat))
Most compact method is to use chain() method from itertools module
L1=[[1,2,3],[4,5],[6,7,8,9]] import itertools flat=itertools.chain.from_iterable(L1) print (list(flat))
All the above codes produce a flattened list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- Related Questions & Answers
- How to join two lists in C#?
- Python - Convert List of lists to List of Sets
- Convert list into list of lists in Python
- How to get length of a list of lists in Python?
- Java Program to Join Two Lists
- How to join or concatenate two lists in C#?
- How to append list to second list (concatenate lists) in Python?
- Python - Ways to iterate tuple list of lists
- How do make a flat list out of list of lists in Python?
- Custom Multiplication in list of lists in Python
- Python - Column deletion from list of lists
- Python - Convert column to separate elements in list of lists
- Find common elements in list of lists in Python
- Python - Join tuple elements in a list
- Java program to join two given lists in Java
Advertisements