Python Program to Filter List of Strings and Numbers

  • Post author:
  • Post category:Python
  • Reading time:2 mins read

Here is a Python program to filter a list of strings and numbers.

Filter List of Strings and Numbers Using Python

The following Python program, the first example is to filter all positive numeric values and the second example to filter all negative numeric values. Also replacing negative and positive values with 0. And an example to filter a list of strings.

alist = [1, 5, -5, 9, -8, 4, 3, -1]

# filter all positive values
pos = [n for n in alist if n > 0]
print(pos)

# filter all negative values
neg = [n for n in alist if n < 0]
print(neg)

# Negative values replace to 0
neg_clip = [n if n > 0 else 0 for n in alist]
print(neg_clip)

# Positive values replace to 0
pos_clip = [n if n < 0 else 0 for n in alist]
print(pos_clip)

# Compression example

fruits = [
    'APPLE',
    'MANGO',
    'PEACH',
    'ORANGE',
    'BANANA',
    'PINEAPPLE',
    'GRAPES',
    'GREEN APPLE',
]

counts = [ 0, 3, 10, 4, 1, 7, 6, 1]

from itertools import compress

more5 = [ n > 5 for n in counts ]
a = list(compress(fruits, more5))
print(a)

Output:

[1, 5, 9, 4, 3]
[-5, -8, -1]
[1, 5, 0, 9, 0, 4, 3, 0]
[0, 0, -5, 0, -8, 0, 0, -1]
['PEACH', 'PINEAPPLE', 'GRAPES']

Process finished with exit code 0

See also:

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.