﻿ Python: Filter the positive numbers from a list - w3resource

# Python: Filter the positive numbers from a list

## Python Basic: Exercise-114 with Solution

Write a Python program to filter positive numbers from a list.

Positive Numbers: Any number above zero is known as a positive number. Positive numbers are written without any sign or a '+' sign in front of them and they are counted up from zero, i.e. 1, + 2, 3, +4 etc.

Pictorial Presentation:

Sample Solution-1:

Python Code:

``````# Define a list named "nums" containing a series of integers.
nums = [34, 1, 0, -23, 12, -88]

# Print a message along with the original list of numbers.
print("Original numbers in the list: ", nums)

# Create a new list "new_nums" by using the "filter" function with a lambda function
# that filters out positive numbers from the "nums" list.
new_nums = list(filter(lambda x: x > 0, nums))

# Print a message along with the list of positive numbers from the "nums" list.
print("Positive numbers in the said list: ", new_nums)
```
```

Sample Output:

```Original numbers in the list:  [34, 1, 0, -23, 12, -88]
Positive numbers in the said list:  [34, 1, 12]
```

Sample Solution-2:

Python Code:

``````# Define a list named "nums" containing a series of integers.
nums = [34, 1, 0, -23, 12, -88]

# Print a message along with the original list of numbers.
print("Original numbers in the list: ", nums)

# Print a message indicating that positive numbers in the list will be listed.
print("Positive numbers in the said list: ")

# Iterate through each number in the "nums" list.
for pos_nums in nums:
# Check if the number is greater than 0 (positive).
if pos_nums > 0:
# Print positive numbers on the same line with a space separator.
print(pos_nums, end=" ")
```
```

Sample Output:

```Original numbers in the list:  [34, 1, 0, -23, 12, -88]
Positive numbers in the said list:
34 1 12
```

Flowchart:

Sample Solution-3:

Python Code:

``````# Define a list named "nums" containing a series of integers.
nums = [34, 1, 0, -23, 12, -88]

# Print a message along with the original list of numbers.
print("Original numbers in the list: ", nums)

# Create a new list "pos_nums" using a list comprehension to filter positive numbers from "nums."
# Positive numbers are those greater than 0.
pos_nums = [n for n in nums if n > 0]

# Print a message indicating that positive numbers in the list will be listed,
# followed by the positive numbers separated by a space.
print("Positive numbers in the said list: ", *pos_nums)
```
```

Sample Output:

```Original numbers in the list:  [34, 1, 0, -23, 12, -88]
Positive numbers in the said list:  34 1 12
```

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿