Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a subset of a list that matches a condition [duplicate]

Let's say I have a list of ints:

listOfNumbers = range(100) 

And I want to return a list of the elements that meet a certain condition, say:

def meetsCondition(element):     return bool(element != 0 and element % 7 == 0) 

What's a Pythonic way to return a sub-list of element in a list for which meetsCondition(element) is True?

A naive approach:

def subList(inputList):     outputList = []      for element in inputList:         if meetsCondition(element):             outputList.append(element)      return outputList  divisibleBySeven = subList(listOfNumbers) 

Is there a simple way to do this, perhaps with a list comprehension or set() functions, and without the temporary outputList?

like image 440
Will Avatar asked Jan 30 '16 11:01

Will


People also ask

How do you split a list based on a condition in Python?

split() , to split the list into an ordered collection of consecutive sub-lists. E.g. split([1,2,3,4,5,3,6], 3) -> ([1,2],[4,5],[6]) , as opposed to dividing a list's elements by category. Discussion of the same topic on python-list. IMAGE_TYPES should be a set instead of a tuple: IMAGE_TYPES = set('.

How do you find the subset of a list?

USE set. issubset() TO CHECK IF A LIST IS A SUBSET OF ANOTHER LIST Use set(list) to convert the lists to sets. Call set1. issubset(set2) to return a Boolean indicating whether set1 is a subset of set2.

How do you check if a list is subset to another list in Python?

if res = = True : print ( "Yes, list is subset of other." ) else : print ( "No, list is not subset of other." )


1 Answers

Use list comprehension,

divisibleBySeven = [num for num in inputList if num != 0 and num % 7 == 0] 

or you can use the meetsCondition also,

divisibleBySeven = [num for num in inputList if meetsCondition(num)] 

you can actually write the same condition with Python's truthy semantics, like this

divisibleBySeven = [num for num in inputList if num and num % 7] 

alternatively, you can use filter function with your meetsCondition, like this

divisibleBySeven = filter(meetsCondition, inputList) 

%timeit

listOfNumbers = range(1000000)  %timeit [num for num in listOfNumbers if meetsCondition(num)] [out]: 243 ms ± 4.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)  %timeit list(filter(meetsCondition, listOfNumbers)) [out]: 211 ms ± 4.19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 
like image 76
thefourtheye Avatar answered Oct 11 '22 08:10

thefourtheye