Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key

What is Tuple in Python?

A tuple is just like a list of a sequence of immutable python objects. The difference between list and tuple is that list are declared in square brackets and can be changed while tuple is declared in parentheses and cannot be changed. However, you can take portions of existing tuples to make new tuples.

Tuple Syntax

Tuple indices begin at 0, and they can be concatenated, sliced and so on.

In this tutorial, we will learn-

Tuple Assignment

Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have assigned tuple 1 with the persons information like name, surname, birth year, etc. and another tuple 2 with the values in it like number (1,2,3,….,7).

For Example,

(name, surname, birth year, favorite movie and year, profession, birthplace) = Robert

Here is the code,

Comparing tuples

A comparison operator in Python can work with tuples.

The comparison starts with a first element of each tuple. If they do not compare to =,< or > then it proceed to the second element and so on.

It starts with comparing the first element from each of the tuples

 

Built-in functions with Tuple

To perform different task, tuple allows you to use many built-in functions like all(), any(), enumerate(), max(), min(), sorted(), len(), tuple(), etc.

Advantages of tuple over list

  • Iterating through tuple is faster than with list, since tuples are immutable.
  • Tuples that consist of immutable elements can be used as key for dictionary, which is not possible with list
  • If you have data that is immutable, implementing it as tuple will guarantee that it remains write-protected

Summary:

Python has tuple assignment feature which enables you to assign more than one variable at a time.

  • Packing and Unpacking of Tuples
    • In packing, we place value into a new tuple while in unpacking we extract those values back into variables.
  • A comparison operator in Python can work with tuples.
  • Using tuples as keys in dictionaries
    • Tuples are hashable, and list are not
    • We must use tuple as the key if we need to create a composite key to use in a dictionary
    • Dictionary can return the list of tuples by calling items, where each tuple is a key value pair
  • Tuples are immutable and cannot be deleted. You cannot delete or remove items from a tuple. But deleting tuple entirely is possible by using the keyword “del”
  • To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing
top
X
Welcome to Our Website
Welcome to WPBot
wpChatIcon