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 - Nested List to single value Tuple
In Python, converting a nested list to a single-value tuple means extracting all elements from sublists and wrapping each element in its own tuple. This operation is useful in data processing and competitive programming scenarios.
Understanding the Problem
We need to convert a nested list like [[1, 2], [3, 4]] into single-value tuples like [(1,), (2,), (3,), (4,)]. Each element becomes a tuple containing only that single value.
Method 1: Using reduce() Function
The reduce() function from functools can flatten the nested list, then we create single-value tuples ?
from functools import reduce
def convert_with_reduce(nested_list):
# Flatten the nested list using reduce
flat_list = reduce(lambda a, b: a + b, nested_list)
# Create single-value tuples
result = [(item,) for item in flat_list]
return result
# Example usage
nested_data = [[12, 20], [15, 17, 16], [36], [45, 87]]
print("Input:", nested_data)
output = convert_with_reduce(nested_data)
print("Output:", output)
Input: [[12, 20], [15, 17, 16], [36], [45, 87]] Output: [(12,), (20,), (15,), (17,), (16,), (36,), (45,), (87,)]
Method 2: Using Nested Loops
A straightforward approach using nested for loops to iterate through each sublist and element ?
def convert_with_loops(nested_list):
result = []
for sublist in nested_list:
for item in sublist:
result.append((item,))
return result
# Example with multiple test cases
test_data = [[1, 5, 6], [4, 8, 9]]
output1 = convert_with_loops(test_data)
print("Test 1:", output1)
test_data2 = [[12, 14, 16, 18]]
output2 = convert_with_loops(test_data2)
print("Test 2:", output2)
Test 1: [(1,), (5,), (6,), (4,), (8,), (9,)] Test 2: [(12,), (14,), (16,), (18,)]
Method 3: Using List Comprehension
A more Pythonic approach using nested list comprehension for cleaner, more readable code ?
def convert_with_comprehension(nested_list):
return [(item,) for sublist in nested_list for item in sublist]
# Example usage
data = [[10, 20], [30, 40, 50], [60]]
result = convert_with_comprehension(data)
print("Input:", data)
print("Output:", result)
Input: [[10, 20], [30, 40, 50], [60]] Output: [(10,), (20,), (30,), (40,), (50,), (60,)]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| reduce() | O(n) | O(n) | Moderate |
| Nested Loops | O(n) | O(n) | High |
| List Comprehension | O(n) | O(n) | Very High |
Conclusion
List comprehension provides the most Pythonic and readable solution for converting nested lists to single-value tuples. All methods have similar performance, but list comprehension offers the cleanest syntax for this common data transformation task.
---