- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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]]
- Related Articles
- Get last N elements from given list in Python
- Program to interleave list elements from two linked lists in Python
- Find common elements in list of lists in Python
- Python - Convert column to separate elements in list of lists
- Check if a list exists in given list of lists in Python
- Python - Column deletion from list of lists
- How to get length of a list of lists in Python?
- Python – Calculate the percentage of positive elements of the list
- Python program to find Tuples with positive elements in List of tuples
- Convert list into list of lists in Python
- Python – Filter rows with only Alphabets from List of Lists
- Check if is possible to get given sum from a given set of elements in Python
- Find frequency of given character at every position in list of lists in Python
- Python program to find Tuples with positive elements in a List of tuples
- Python - Ways to format elements of given list
