How to Get All Elements Less Than Some Value in Python List?

02-May-2023

.

Admin

How to Get All Elements Less Than Some Value in Python List?

Hi Dev,

In this tutorial, I will show you how to get all elements less than some value in a Python list. step by step explain the Python list to get all elements less than some value. Here you will learn Python list get values less than certain value. In this article, we will implement Python for all items in the list less than others. So, let's follow a few steps to create an example of getting items less than the value in a Python list.

There are several ways to get all items less than a certain value. In this example, we will get all values that are less than the "7" value. we will use a filter and sorted() to get elements that are less than other values. so let's see the below examples.

Example 1:


main.py

# Create New List with Item

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# Python list get all elements less than some value

newList = [item for item in myList if item < 7]

print(newList)

Output:

[1, 2, 3, 4, 5, 6]

Example 2:

main.py

# Create New List with Item

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# Python list get all elements less than some value

newList = sorted(item for item in myList if item < 9)

print(newList)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

#Python