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
Get positive elements from given list of lists in Python
Lists can be nested, meaning the elements of a list are themselves lists. In this article we will see how to extract only the positive numbers from a list of lists. The result will be a new list containing nested lists with only positive numbers.
Using List Comprehension
List comprehension provides a concise way to filter positive elements from nested lists. We use nested list comprehension to iterate through each sublist and filter elements greater than zero ?
Example
listA = [[-9, -1, 3], [11, -8, -4, 434, 0]]
# Given list
print("Given List :")
print(listA)
# Finding positive elements using list comprehension
res = [[y for y in x if y > 0] for x in listA]
# Result
print("List of positive numbers :", res)
The output of the above code is ?
Given List : [[-9, -1, 3], [11, -8, -4, 434, 0]] List of positive numbers : [[3], [11, 434]]
Using Nested Loops with append()
The append() method allows us to keep adding elements to a list. Here we use nested for loops where the inner loop tests each element for positivity and appends it to a temporary list, while the outer loop processes each sublist ?
Example
listA = [[-9, -1, 3], [11, -8, -4, 434, 0]]
# Given list
print("Given List :")
print(listA)
res = []
# With nested loops and append
for elem in listA:
temp = []
for i in elem:
if i > 0:
temp.append(i)
res.append(temp)
# Result
print("List of positive numbers :", res)
The output of the above code is ?
Given List : [[-9, -1, 3], [11, -8, -4, 434, 0]] List of positive numbers : [[3], [11, 434]]
Using filter() Function
The filter() function provides another approach to extract positive elements. We apply filter to each sublist and convert the result back to a list ?
Example
listA = [[-9, -1, 3], [11, -8, -4, 434, 0]]
# Given list
print("Given List :")
print(listA)
# Using filter function
res = [list(filter(lambda x: x > 0, sublist)) for sublist in listA]
# Result
print("List of positive numbers :", res)
The output of the above code is ?
Given List : [[-9, -1, 3], [11, -8, -4, 434, 0]] List of positive numbers : [[3], [11, 434]]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Concise filtering |
| Nested Loops | Medium | Moderate | Complex logic |
| filter() | Medium | Fast | Functional programming |
Conclusion
List comprehension is the most Pythonic and efficient way to extract positive elements from nested lists. Use nested loops when you need more complex logic, and filter() for functional programming approaches.
