Currently running with:
l1 = [i for i in range(0,10)]
l2 = [i for i in range(0,10)]
l3 = [i for i in range(0,10)]
lists = [l1, l2, l3]
length = len(lists[0])
for l in lists:
if length != len(l):
raise ValueErrorr('not all lists have same length!')
Is there a prettier way to test for this than a for
loop? Is there a faster/better way which isn't O(n)
?
I'd do it with a generator expression and all
:
it = iter(lists)
the_len = len(next(it))
if not all(len(l) == the_len for l in it):
raise ValueError('not all lists have same length!')
This avoids checking the length of the first list twice and does not build throwaway list/set datastructures.
all
also evaluates lazily, which means it will stop and return False
as soon as the first list which differs in length is yielded by the generator.
You can use a set comprehension in order to preserve the unique lengths, then check if you only have one item in set:
if len({len(i) for i in lists}) == 1:
# do stuff
Or as a more efficient way you could use a generator expression within any
or all
.
def check_size_eq(lst):
# returns true if there's any list with unequal length to the first one
return not any(len(lst[0])!= len(i) for i in lst)
# or you could do:
# return all(len(lst[0])== len(i) for i in lst)
demo :
>>> a = {1}
>>>
>>> a.pop() and not a
True
>>> a = {1,3}
>>> a.pop() and not a
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With