This tutorial will discuss about unique ways to get a sublist from a list based on certain conditions in Python.
Table Of Contents
Method 1: Using filter() method
Create a lambda function, that accepts a element as argument, and returns True if that element satisfies a given condition, otherwise returns False.
Pass this lambda function to filter() method along with a list. It will return only those elements from list for which this lambda function returns True. Collect those elements in a new list i.e. a new list containing only those elements from list, that satisfies the given condition.
Example 1: Get a sublist containing only odd numbers from list.
Let’s see the complete example,
listOfIntegers = [12, 42, 78, 68, 91, 72, 71, 81, 82] # Get a sublist of only odd numbers from list subList = list(filter(lambda elem: elem % 2 == 1, listOfIntegers)) print(subList)
Output
[91, 71, 81]
Example 2: Get a sublist containing numbers between 70 to 80 from the list.
Let’s see the complete example,
Frequently Asked:
listOfIntegers = [12, 42, 78, 68, 91, 72, 71, 81, 82] # Get a sublist of only numbers between 70 to 80 subList = list(filter(lambda elem: elem > 70 and elem < 80, listOfIntegers)) print (subList)
Output
[78, 72, 71]
Method 2: Using List Comprehension
Use list comprehension to apply a condition on each element of list, and select only those elements for which the condition evaluates to True
.
Example 1: Get a sublist containing only odd numbers from list.
Let’s see the complete example,
listOfIntegers = [12, 42, 78, 68, 91, 72, 71, 81, 82] # Get a sublist of only odd numbers from list subList = [elem for elem in listOfIntegers if elem % 2 == 1] print (subList)
Output
[91, 71, 81]
Example 2: Get a sublist containing numbers between 70 to 80 from the list.
Let’s see the complete example,
listOfIntegers = [12, 42, 78, 68, 91, 72, 71, 81, 82] # Get a sublist of only numbers between 70 to 80 subList = [elem for elem in listOfIntegers if elem > 70 and elem < 80] print (subList)
Output
[78, 72, 71]
Summary
We learned about different ways to get a sublist from a List based on conditions in Python. Thanks.