HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python unpack tuple into variables or arguments

Python unpack tuple into variables or arguments

Python examples to unpack an N-element tuple or sequence into a collection of N variables. Python example to unpack tuple into variables.

1. Python unpack tuple example

Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence.

1.1. Unpack example – 1

>>> data = (1, 2, 3)
>>> x, y, z = data
>>> x
1
>>> y
2
>>> z
3

1.2. Unpack example – 2

>>> data = [ 'Lokesh', 37, 73.5, (1981, 1, 1) ]

>>> name, age, weight, dob = data

>>> name
'Lokesh'
>>> dob
(1981, 1, 1)

# Another Variation

>>> name, age, weight, (year, mon, day) = data

>>> name
'Lokesh'
>>> year
1981
>>> mon
1
>>> day
1

1.3. Unpack example – 3

>>> greeting = 'Hello'

>>> a, b, c, d, e = greeting

>>> a
'H'	
>>> b
'e'
>>> c
'o'

2. Possible error while unpacking

If there is a mismatch in the number of elements, you’ll get an error.

>>> p = (4, 5)

>>> x, y, z = p

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

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 Examples

  • Python Hello World
  • Python Dictionary Intersection
  • Python Unpacking Tuple
  • Python Find Largest N Items
  • Python Finding Max and Min
  • Python Print to File
  • Python Print Without Newline
  • Python Print List

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

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)