Python Forum

Full Version: test interable if len == 2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
a function gets a likely iterable. how can i test if it really has a len == 2 when it does not support len(), such as a generator? how does dict() do it? would it be appropriate to just let dict() do the test for me, in a try/except for cases where i need to run certain code when it has the wrong len, making a dictionary i might just throw away? oh wait, i might get an item #0 that is not valid as a dictionary key (cannot be hashed, such as a bytearray).
Why not try to consume 3 elements and store in variables? If you get third value or just zero/one - raise exception or whatever you would do if it is not of len 2.
can i do that in a comprehension ...consume up to 3 but no more than 3 and collect them in a list? that would simplify a few things.

maybe:
itlist = [next(myiter) for x in range(3)]
could that raise an exception or would it just give me a list of the right length. if the iterable has 351769 possible items i don't want to iterate over all of them ... just 3 at most.
from itertools import islice

my_iter = range(65536)
my_elements = list(islice(my_iter, 0, 3))

if len(my_elements) != 3:
    raise IndexError('Iterable has to less elements.')
The function islice is like the range function, but for iterators and iterables.
(Iterators are iterable, but iterables does not have to be iterators)
It does not raise an exception, if the iterable is exhausted before the end (3rd element) has been reached.
You have to check, if you've consumed the expected amount of elements.
because Skaperen wants exactly len 2:
if len(my_elements) != 2:
    raise IndexError('Iterable must have 2 elements')
or

assert len(my_elements) == 2, 'Iterable must have 2 elements.'