How to return a subset of a list that matches a condition

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to return a subset of a list that matches a condition in Python. So Here I am Explain to you all the possible Methods here.

How to return a subset of a list that matches a condition?

1. How to return a subset of a list that matches a condition?

Use list comprehension,
divisibleBySeven = [num for num in inputList if num != 0 and num % 7 == 0]

2. return a subset of a list that matches a condition

Use list comprehension,
divisibleBySeven = [num for num in inputList if num != 0 and num % 7 == 0]

Method 1

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)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.