Let's say I have a list of int
s:
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 with a list comprehension or set()
functions, and without the temporary outputList?
Use list comprehension,
or you can use the
meetsCondition
also,you can actually write the same condition with Python's truthy semantics, like this
alternatively, you can use
filter
function with yourmeetsCondition
, like this