Sunday, October 27, 2019

Tuples in Python:

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).


tup1 = ('Robert', 'Carlos','1965','Terminator 1995', 'Actor','Florida');
tup2 = (1,2,3,4,5,6,7);
print(tup1[0])
print(tup2[1:4])


Packing and Unpacking

x = ("Guru99", 20, "Education")    # tuple packing
(company, emp, profile) = x    # tuple unpacking
print(company)
print(emp)
print(profile)


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.

a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")

Using tuples as keys in dictionaries


Since tuples are hashable, and list is not, we must use tuple as the key if we need to create a composite key to use in a dictionary.

directory[last,first] = number

We would come across a composite key if we need to create a telephone directory that maps, first-name, last-name, pairs of telephone numbers, etc. Assuming that we have declared the variables as last and first number, we could write a dictionary assignment statement as shown below:

Inside the brackets, the expression is a tuple. We could use tuple assignment in a for loop to navigate this dictionary.

for last, first in directory:
print first, last, directory[last, first]

Deleting Tuples

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

Slicing of Tuple

To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing. Slicing is not only applicable to tuple but also for array and list.

x = ("a", "b","c", "d", "e")
print(x[2:4])

The output of this code will be ('c', 'd').

There are few built in methods for tuple and they are:

all(), any(), enumerate(), max(), min(), sorted(), len(), tuple()

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



References:
https://www.guru99.com/python-tuples-tutorial-comparing-deleting-slicing-keys-unpacking.html

No comments:

Post a Comment