# Get positive elements from given list of lists in Python

Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out only the positive numbers from a list of lists. In the result a new list will contain nested lists containing positive numbers.

## With for in

Here we simply apply the mathematical operator to check for the value of elements in a list using a for loop. If the value is positive we capture it as a list and Outer for loop stores as a final list of lists.

## Example

Live Demo

listA = [[-9, -1, 3], [11, -8, -4,434,0]]

# Given list
print("Given List :\n", listA)

# Finding positive elements
res = [[y for y in x if y > 0] for x in listA]

# Result
print("List of positive numbers :", res)

## Output

Running the above code gives us the following result −

Given List :
[[-9, -1, 3], [11, -8, -4, 434, 0]]
List of positive numbers : [[3], [11, 434]]

## With append

The append function blouses to keep adding elements into a container. Here we design nested for loop in which we test for the value of the element to be positive and append it to a list in the inner for loop while the outer for loop captures each of the inner sublists.

## Example

Live Demo

listA = [[-9, -1, 3], [11, -8, -4,434,0]]

# Given list
print("Given List :\n", listA)

res= []

# With 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)

## Output

Running the above code gives us the following result −

Given List :
[[-9, -1, 3], [11, -8, -4, 434, 0]]
List of positive numbers : [[3], [11, 434]]

Updated on: 13-May-2020

330 Views