Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Convert column to separate elements in list of lists
When working with data structures in Python, you often need to reshape lists by separating columns into different elements. This is particularly useful when converting tabular data into different formats or extracting specific column ranges from nested lists.
Using List Slicing and Comprehension
You can slice lists at specific positions to create a columnar structure. This approach splits each sublist into two parts: elements from index 2 onwards and elements from index 0 to 2 ?
Example
data = [[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]]
print("The given input is:")
print(data)
# Using list slicing and list comprehension
result = [m for y in [[n[2:], [n[0:2]]] for n in data] for m in y]
print("Converting column to separate elements in list of lists:")
print(result)
The output of the above code is ?
The given input is: [[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]] Converting column to separate elements in list of lists: [[15, 20], [[5, 10]], [35, 40], [[25, 30]], [55, 60], [[45, 50]]]
Using itertools.chain() and List Comprehension
The itertools.chain() method provides a cleaner approach by flattening the nested structure. This eliminates the need for nested loops while achieving the same column separation ?
Example
from itertools import chain
data = [[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]]
print("The given input is:")
print(data)
# Using itertools.chain() and list comprehension
result = list(chain(*[list((n[2:], [n[0:2]])) for n in data]))
print("Converting column to separate elements in list of lists:")
print(result)
The output of the above code is ?
The given input is: [[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]] Converting column to separate elements in list of lists: [[15, 20], [[5, 10]], [35, 40], [[25, 30]], [55, 60], [[45, 50]]]
How It Works
Both methods split each sublist into two parts:
-
n[2:]− Elements from index 2 to the end -
[n[0:2]]− Elements from index 0 to 1, wrapped in a list
The comprehension processes each sublist and creates pairs, which are then flattened into a single result list.
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | Complex | Good | Simple transformations |
| itertools.chain() | Better | Excellent | Flattening nested structures |
Conclusion
Use itertools.chain() for better readability and performance when flattening nested lists. List comprehension works well for simple column separation tasks but can become complex with nested structures.
