- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Python program to print negative numbers in a list
In this article, we will learn about the solution and approach to solve the given problem statement.
Problem statement
Given a list iterable, we need to print all the negative numbers in the list.
Here we will be discussing three approaches for the given problem statement.
Approach 1 − Using enhanced for loop
Example
list1 = [-11,23,-45,23,-64,-22,-11,24] # iteration for num in list1: # check if num < 0: print(num, end = " ")
Output
-11 -45 -64 -22 -11
Approach 2 − Using filter & lambda function
Example
list1 = [-11,23,-45,23,-64,-22,-11,24] # lambda exp. no = list(filter(lambda x: (x < 0), list1)) print("Negative numbers in the list: ", no)
Output
Negative numbers in the list: [-11 -45 -64 -22 -11]
Approach 3 − Using list comprehension
Example
list1 = [-11,23,-45,23,-64,-22,-11,24] #list comprehension nos = [num for num in list1 if num < 0] print("Negative numbers in the list: ", nos)
Output
Negative numbers in the list: [-11 -45 -64 -22 -11]
Conclusion
In this article, we learned about the approach to print negative numbers in the input list.
Advertisements