Iterable Unpacking in Python #PyTip02

Problem

primes = [2, 3, 5, 7, 11]
first, second, third = primes
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ValueError: too many values to unpack (expected 3)

Solution

>>> primes = [2, 3, 5, 7, 11]
>>> first, second, third, *_ = primes
>>> print(first, second, third, _)
2 3 5 [7, 11]
>>> primes = [2, 3, 5, 7, 11]
>>> first, *_ , last = primes
>>> print(first, last, _)
2 11 [3, 5, 7]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vivek

Vivek

I am a leaner. Python Programmer. Creating content around Python and Web Development