Python unpack tuple – too many values to unpack

Python example to unpack tuple or sequence or iterable such that the tuple may be longer than N elements, causing a “too many values to unpack” exception.

1. Unpack tuple with arbitrary length

Python “star expressions” can be used to to unpack tuples with arbitrary length.

>>> employee = ('Lokesh', '', '111-222-333', '444-555-666')

>>> name, email, *phone_numbers = employee

>>> name
>>> email
>>> phone_numbers
['111-222-333', '444-555-666']
>>> *elements, end = [1,2,3,4,5,6,7,8]

>>> elements

>>> end

2. Unpack tuple and throw away unwanted values

Sometimes you might want to unpack values and throw them away. You can’t just specify a bare * when unpacking, but you could use a common throwaway variable name, such as “_” or ignore.

>>> record = ('Lokesh', 37, 72.45, (1, 1, 1981))

>>> name, *_, (*_, year) = record	#Only read name and year

>>> name

>>> year

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.