Reputation: 396
please consider following code snippet:
# state that items contains two or more elements
x, y, *_ = items
# state that items contains exactly two elements
x, y, = items
# state that items contains exactly one element
x, = items
Can I state that items
contains exactly zero elements in the similar way?
Thanks in advance!
Upvotes: 1
Views: 206
Reputation: 107307
Not in a similar way but you can try to do access to the iterable's first item. If it raised an exception the iterable is empty. This method is famous as EAFP manner (Easier to ask for forgiveness than permission.). Or you can check if iterable is empty or not by checking the boolean value if the iterable. With that being said, for an iterator you can use next()
method, for iterables you can use indexing (__getitem__
), etc.
# Easier to ask for forgiveness than permission.
In [41]: try:
...: item[0]
...: except:
...: print("empty list")
empty list
# Or
In [45]: items = iter([])
In [46]: try:
...: next(items)
...: except StopIteration:
...: print("empty list")
...:
empty list
Upvotes: 0
Reputation: 16414
You can use:
() = items
ValueError
will raise if items
has more than 0 elements.
This is valid in Python 3.6:
>>> items = []
>>> () = items
>>> items = [1,2]
>>> () = items
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 0)
Upvotes: 1