Given a list, I wanted to check if all the elements in that list are divisible by some given integer or not. Based on that, i have to return a boolean value.
l=[10,30,40,20]
For example – all the elements of this list are divisible by 5. Then, I would return True.
For 6, I would have returned False.
One approach I could think of is to generate an array consisting off boolean values and then AND them.
blist=[x%5==0 for x in l]
# [False, False, False, False]
# AND THE ELEMENTS
But this approach kind of feels bad. Can anyone suggest a more simple pythonic way out of this.
First of all, you want modulo division (
%) as you want to see if it evenly divides by5, so you are checking for a remainder, not the result of division.You can use the
all()builtin (which does what it says on the tin), but you don’t need to generate a list, instead use a generator expression:This has the advantage of being lazy, so as soon as a value isn’t divisible it will return, saving computation