Tricky Unpacking In Python
Imagine, you iterate through a collection, which contains some other collections.
Like so: list of lists
One obvious way to iterate over inner values is to use indexing:
Well, there is another way to do so. Almost so :)
In fact, it is single element unpacking. It works, because in python commas, not brackets, “construct” tuples.
Are there any differences?
Yeap.
This unpacking seems to be faster than reading by index. Not much, by ~10%.
Also, there is logical difference.
If we take a list of empty lists as input, both statements will fall with different exceptions:
However, if we have more than 1 element in any of inner lists, then:
- unpacking will fall with
ValueError: too many values to unpack (expected 1)
- and reading by index will silently return first elements of lists
“Explicit is better than implicit” - they say, huh?
Hope you enjoyed! :)
Anything else to read?
Sure.
Python docs on unpacking - click, click и click
Comments to this article on my DEV.to - consider subscribing, by the way :)