Python Tuple and Dictionary

  • By Karishma Pawar
  • December 29, 2023
  • Python
Python Tuple and Dictionary

Python Tuple and Dictionary

Python, a versatile and expressive programming language, offers powerful features that make code concise and readable. Two such features are Python Tuple and Dictionary unpacking, allowing developers to work with data in a flexible and efficient manner. 

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Unpacking a Tuple:

A tuple is an ordered collection of elements, and unpacking allows us to extract these elements easily. Consider the following example:

Python Tuple and Dictionary

Output: 

Python Tuple and Dictionary

In this example, each variable on the left side of the assignment operator corresponds to an element in the tuple. The values are unpacked in order, providing a convenient way to access individual elements.

Unpacking a Dictionary:

Dictionaries in Python are collections of key-value pairs, and unpacking them allows us to access both keys and values effortlessly. Let’s explore dictionary unpacking:

Python Tuple and Dictionary

Output: 

Python Tuple and Dictionary

 

For Free, Demo classes Call: 02071171500

Registration Link: Python Training in Pune!

 

Use of * for Unpacking tuple:

Unpacking a tuple can be particularly useful in function parameters. Here is an example of how you can unpack a tuple within a function:

Python Tuple and Dictionary

Output: 

This demonstrates how you can leverage tuple unpacking to pass multiple values to a function in a concise and readable manner. The number and order of variables in the function parameters should match the number and order of elements in the tuple for successful unpacking.

Python Tuple and Dictionary

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Use of ** for Unpacking a dictionary :

Unpacking a dictionary in a function involves using the ** operator to pass the key-value pairs of the dictionary as keyword arguments. Here is an example:

Python Tuple and Dictionary

Output: 

Python Tuple and Dictionary

Visit our channel to learn more: Click Here

This demonstrates how you can use dictionary unpacking to pass named parameters to a function based on the keys of the dictionary. The keys in the dictionary should match the parameter names of the function for successful unpacking. Explore more about Top 50+ Python Interview Questions and Answers.

Author:

Karishma Pawar

Call the Trainer and Book your free demo Class For Python Call now!!!
| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*