Python create list from list with condition

In this example we will discuss 4 different ways to count number of elements in a list that satisfy certain conditions.

Suppose we have a list of numbers i.e.

# List of numbers listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101]
We want to count number of elements in the list that satisfy our given conditions. These conditions can be like,
  • Number should be Odd i.e. x % 2 == 1
  • Number should be Even i.e. x % 2 == 0
  • Number should be greater than five i.e. x > 5
  • Number should be greater than five and less than twenty i.e. x > 5 and x < 20

There are different ways to do it. Lets discuss them one by one,

Use map[] & sum[] to count elements in a list that satisfy certain conditions

map[] function

map[function, iterable, ...]
map[] Function in python accepts a function and an iterable like list. Then applies the given function to each element in the list and appends the result of function in a new list. In the end map[] returns this new list i.e. list of results.

sum[] Function

sum[iterable, start=0]
sum[] function adds the items in the given iterable.

Lets use both of these functions to count elements in a list by condition.

Count odd numbers in the list

Single line solution is,

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # Count odd numbers in the list count = sum[map[lambda x : x%2 == 1, listOfElems]] print['Count of odd numbers in a list : ', count]
Output:
Count of odd numbers in a list : 6
How did it worked ?

Lets break the above solution in small steps to understand how it worked.

In this case our condition is that number should be odd. So, lets create a lambda function that checks this condition i.e.

lambda x : x%2 == 1
Now pass our condition / lambda function to map[] and get a map object of results i.e.
mapObj = map[lambda x : x%2 == 1, listOfElems]
The given lambda function is applied to each element in the list and result is stored in the map object. As our lambda function returns a a bool, so map object contains bool elements. We can check the result by printing map object contents i.e.
print['Contents of map object : ', list[mapObj]]
Output:
Contents of map object : [True, False, True, True, False, True, False, True, True]
Number of True in this bool list represents the count of odd elements in the list. Lets count the occurrences of True in this map object using sum[] function i.e.
# Add number of True / 1 in the map object of bools count = sum[mapObj]
This is how we found count of elements in list that satisfies a given condition.

Lets see some more examples to count elements in list based on conditions using sum[] & map[]

Count even numbers in the list

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # Count even numbers in the list count = sum[map[lambda x : x%2 == 0, listOfElems]] print['Count of even numbers in a list : ', count]
Output:
Count of even numbers in a list : 3

Count numbers in a list which are greater than 5

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = sum[map[lambda x : x>5, listOfElems]] print['Count of numbers in a list which are greater than 5: ', count]
Output:
Count of numbers in a list which are greater than 5: 9

Use sum[] & Generator expression to count elements in list based on conditions

Lets create a function that uses sum[] & Generator Expression to count number of elements in a list that satisfies our given condition i.e.

def getCount[listOfElems, cond = None]: 'Returns the count of elements in list that satisfies the given condition' if cond: count = sum[cond[elem] for elem in listOfElems] else: count = len[listOfElems] return count
This function accepts a list and a callback function as argument. Callback function will be our function that checks the condition. This function calls the given callback function on each element in the list and returns a count of elements in list that returns True when passed to our condition i.e. callback.

Lets use this function to count number of elements in list that satisfies our condition,

Count numbers in a list which are greater than 5:

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = getCount[listOfElems, lambda x : x>5] print['Count of numbers in a list which are greater than 5: ', count]
Output:
Count of numbers in a list which are greater than 5: 9

Count numbers in a list which are greater than 5 but less than 20:

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 but less than 20 count = getCount[listOfElems, lambda x : x>5 and x < 20] print['Count of numbers in a list which are greater than 5 but less than 20 : ', count]
Output:
Count of numbers in a list which are greater than 5 but less than 20 : 1
If no callback function is passed then this function will return the total number of elements in the list i.e.

Count total number of elements in the list

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # Get total number of elements in the list count = getCount[listOfElems] print['Total Number of elements in List: ', count]
Output
Total Number of elements in List: 9

Use len[] & List comprehension to count elements in list based on conditions

We can use list comprehension to create a new list of elements that satisfies our given condition and then get the length of this new list to find out number of elements in original list that satisfies our condition i.e.

Count numbers in a list which are greater than 5

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = len[[elem for elem in listOfElems if elem > 5]] print['Count of numbers in a list which are greater than 5: ', count]
Output:
Count of numbers in a list which are greater than 5: 9

Use reduce[] function to count elements in list based on conditions

Count of numbers in a list which are greater than 5

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = reduce[lambda default, elem: default + [elem > 5], listOfElems, 0] print['Count of numbers in a list which are greater than 5: ', count]
Output:
Count of numbers in a list which are greater than 5: 9
reduce[] function will iterate over the list check condition & add each True values to count number of elements that satisfies the given condition.

Complete example is as follows,

from functools import reduce def getCount[listOfElems, cond = None]: 'Returns the count of elements in list that satisfies the given condition' if cond: count = sum[cond[elem] for elem in listOfElems] else: count = len[listOfElems] return count def main[]: # List of numbers listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] print['**** Use map[] & sum[] to count elements in a list that satisfy certain conditions ****'] print['** Example 1 **'] # Count odd numbers in the list count = sum[map[lambda x : x%2 == 1, listOfElems]] print['Count of odd numbers in a list : ', count] print['** Example 1 : Explanation **'] # Get a map object by applying given lambda to each element in list mapObj = map[lambda x : x%2 == 1, listOfElems] print['Contents of map object : ', list[mapObj]] print['** Example 2**'] # Count even numbers in the list count = sum[map[lambda x : x%2 == 0, listOfElems]] print['Count of even numbers in a list : ', count] print['** Example 3**'] # count numbers in the list which are greater than 5 count = sum[map[lambda x : x>5, listOfElems]] print['Count of numbers in a list which are greater than 5: ', count] print['**** Using sum[] & Generator expression to count elements in list based on conditions ****'] # count numbers in the list which are greater than 5 count = getCount[listOfElems, lambda x : x>5] print['Count of numbers in a list which are greater than 5: ', count] # count numbers in the list which are greater than 5 but less than 20 count = getCount[listOfElems, lambda x : x>5 and x < 20] print['Count of numbers in a list which are greater than 5 but less than 20 : ', count] # Get total number of elements in the list count = getCount[listOfElems] print['Total Number of elements in List: ', count] print['**** Use List comprehension to count elements in list based on conditions ****'] # count numbers in the list which are greater than 5 count = len[[elem for elem in listOfElems if elem > 5]] print['Count of numbers in a list which are greater than 5: ', count] print['**** Use reduce[] function to count elements in list based on conditions ****'] # count numbers in the list which are greater than 5 count = reduce[lambda default, elem: default + [elem > 5], listOfElems, 0] print['Count of numbers in a list which are greater than 5: ', count] if __name__ == '__main__': main[]
Output:
**** Use map[] & sum[] to count elements in a list that satisfy certain conditions **** ** Example 1 ** Count of odd numbers in a list : 6 ** Example 1 : Explanation ** Contents of map object : [True, False, True, True, False, True, False, True, True] ** Example 2** Count of even numbers in a list : 3 ** Example 3** Count of numbers in a list which are greater than 5: 9 **** Using sum[] & Generator expression to count elements in list based on conditions **** Count of numbers in a list which are greater than 5: 9 Count of numbers in a list which are greater than 5 but less than 20 : 1 Total Number of elements in List: 9 **** Use List comprehension to count elements in list based on conditions **** Count of numbers in a list which are greater than 5: 9 **** Use reduce[] function to count elements in list based on conditions **** Count of numbers in a list which are greater than 5: 9
Advertisements

Video liên quan

Chủ Đề