HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python unpack tuple – too many values to unpack

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', 'email@example.com', '111-222-333', '444-555-666')

>>> name, email, *phone_numbers = employee

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

>>> elements
[1,2,3,4,5,6,7]

>>> end
8

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
'Lokesh'

>>> year
1981

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Tutorial

  • Python Introduction
  • Python Install in Sublime
  • Python Keywords
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python References
  • Python Examples

Python Flow Control

  • Python if…else
  • Python for Loop
  • Python while Loop
  • Python break
  • Python continue
  • Python pass

Python Datatypes

  • Python Integer
  • Python String
  • Python List
  • Python Tuple
  • Python Set
  • Python Dictionary
  • Python OrderedDict
  • Python MultiDict
  • Python Priority Queue

Python Advanced Topics

  • Python Lists vs Tuples
  • Python Comparing Tuples
  • Python Unpacking Tuples
  • Python CSV Files

Python Libraries

  • Python Httplib2

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces