Python: Tuple

 In Python, a tuple is one of the data types that holds the sequence of items. All the items or elements are separated from each other by comma (,) and enclosed in paranthesis(). Although the parentheses are not required, they are recommended.

Features of Python Tuple:

  • Tuples are an immutable data type, meaning their elements cannot be changed after they are formed.
  • Each element in a tuple has a specific order, that will be never changed because tuples are ordered sequences.
Forming a Tuple:
Any number of items, including those with various data types dictionary, string, float, list etc can be contained in a tuple.

Code:

#Python program to show how to create a tuple
#Creating an empty tuple
empty_tuple=()
print("empty tuple:", empty_tuple)

#Creating tuple having integers
int_tuple=(2, 4, 6, 8, 10)
print("tuple with integers:", int_tuple)

#Creating a tuple having objects of different data types
mixed_tuple=(2, "Python", 6.8, 10)
print("tuple with different data types:", mixed_tuple)

#Creating a nested tuple 
nested_tuple=("Python", {6:8, 9:8, 5:2}, (3, 5, 7))
print("A nested tuple:", nested_tuple)


Output:

empty tuple: ()
tuple with integers: (2, 4, 6, 8, 10)
tuple with different data types: (2, "Python", 6.8, 10)
A nested tuple: 
("Python", {6:8, 9:8, 5:2}, (3, 5, 7))

Parentheses are not necessary for the construction of multiples. This is known as tripple pressing.

Code:

#Python program to create a tuple without using parentheses
#Creating the tuple
tuple_=4.2, "Python", ["Lists", "tuples"]
#displaying the tuple 
print(tuple_)
#checking the data type of object tuple_
print(type(tuple_))
#trying to modify the tuple_
try:
    tuple[1]=4.5
except:
    print(TypeError)


Output:

(4.2, "Python", ["Lists", "tuples"])
<class 'tuple'>
<class 'TypeError'>
 Here, some elements are not in brackets, however elements must be seperated by comma(,) to recognize the tuple.

We can verify the above statement by following code: 

Code:

#Python program to show how to create a tuple having single element
#when we don't use comma(,)
tuple_single=("Python")
print(type(tuple_single))

#using of comma(,)
tuple_single=("Python",)
print(type(tuple_single))

#missing of brackets
tuple_single="Python",
print(type(tuple_single))


Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

It is proved by above code that bracket is not but comma(,) is necessary to make a tuple.

Accessing Tuple Elements
A tuple's object can be accessed in a variety of ways:

1. Indexing:
We can use the index operator [] to access an object in a tuple, where the index starts at zero (0). If a tuple has five elements, the index will denote these 0 to 4 respectively. If we try to get the element that is outside the scope like index[5], we get an error message. 
Let's see the above statements in programming:

Code:

#Python program to show indexing.
tup=(5, 7, 6, 8, 9)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[4])
print(tup[5])


Output:

5
7
6
9
IndexError: tuple index out of range

We cannot provide an index of a floating data type. It only works with integers or slices. If we provide a floating index, the result will be TypeError.

Code:

#Python program to show indexing with float.
tup=(5, 7, 6, 8, 9)
print(tup[1.0])


Output:

IndexError: tuple indices must be integers or slices, not float.

Nested Tuple:
In nested tuple the indexing is done by two numbers, First number indicates the tuples, it also starts from zero(0) and second number indicates the element of that particular tuple, it also starts from zero(0).
Let's understand it by codes:

Code:

#Python program to show indexing in nested tuples.
tup_nested=("Pythpn", [4, 3, 2, 1], (5, 7, 6, 8, 9))
print(tup_nested[0][2])
print(tup_nested[1][0])
print(tup_nested[2][4])


Output:

t
4
9

Negative Indexing:
Python tuple supports negative indexing too. It starts from -1 and it indicates the rightmost element of the tuple. -2 indicates the second last and so on.
Let's try it 

Code:

#Python program to show negative indexing in  tuple.
tup_negInd=("orange", "apple", "banana", "mango")
print(tup_negInd[-1])
print(tup_negInd[-3])
print(tup_negInd[-4:-1])


Output:

mango
apple
('orange', 'apple', 'banana')

Slicing:
Slicing is a comman practice in Python and the most comman way for programmers to deal with practical issues.By slicing in Python tuple, we can get only some sequential elements or a part of the tuple which is required.
Let's understand it by codes:

Code:

#Python program to show slicing in Python tuples.
tup_slicing=("orange", "apple", "banana", "mango", "lemon", "papaya")
#to see only first four elements
print(tup_slicing[0:4])
#to see the elements between 2nd and 5th elements
print(tup_slicing[2:5])
#to see the entire tuple
print(tup_slicing[:])


Output:

('orange', 'apple', 'banana', 'mango')
('banana', 'mango', 'lemon')
('orange', 'apple', 'banana', 'mango', 'lemon', 'papaya')

Deleting a Tuple:
As discussed earlier, a tuple's element cannot be modified or removed but we can remove entire tuple by del keyword.

Code:

#Python program to delete a Python tuple.
tup_=("orange", "apple", "banana", "mango", "lemon", "papaya")
print(tup_)
# try to delete only one element
print(del[2])
#to delete entire tuple
del(tup_)
print(tup_)


Output:

('orange', 'apple', 'banana', 'mango', 'lemon', 'papaya')
SyntaxError: invalid syntax
name 'tup_' is not defined

In above output, we tried to delete the 2nd element of the tuple by syntax del[2], but it is recognised as invalid syntax by Python. whereas when we deleted the entire tuple by syntax del(tup_), the tuple is deleted and then we tried to print the tuple, but now it doesnot exist, so the message appears name'tup_' is not defined.

Repeat Tuples in Python:
We can repeat the elements of the  tuple as following example:

Code:

#Python program to show repetition in Python
tup_=("orange", "apple")
print("The original tuple is :", tup_)
# repeting the tuple's element
tup_= tup_*3
print("New tuple is :", tup_)


Output:

The original tuple is : ('orange', 'apple')
New tuple is : ('orange', 'apple', 'orange', 'apple', 'orange', 'apple')

Tuple Methods:
Count() and Indez() methods in Python:
We all know Python tuple is a collection of immutable objects. However there are some ways to work with tuples in Python. These are count() and Index () methods, which are explained here by some examples.

Count() method:

The times the predetermined component happens in the tuple is returned by the count() capability of the Tuple.

Code:

#creating tuples
tup_1=(0, 1, 4, 3, 2, 3, 2, 4, 1, 3, 4, 2)
tup_2=("orange", "apple", "banana", "apple", "orange", "papaya")
# counting the appearance of 2 in tup_1
res= tup_1.count(2)
print("Count of 2 in tup_1:", res)
# counting the appearance of orange in tup_2
res= tup_2.count('orange')
print("Count of orange in tup_2:", res)


Output:

Count of 2 in tup_1: 3
Count of orange in tup_2: 2

Index() Method:
The index() function returns the first instance of the requested element from the Tuple.

Parameters: 
  • The thing that must be looked for.
  • Start: (Optional) the index is used to begin the final (optional) search: the most recent index from which the search is carried out.
  • Index Method
Code:

#creating tuples
tup_1=(0, 1, 4, 3, 2, 3, 2, 4, 1, 3, 4, 2)
#getting the index of 3
res =  tup_1.index(3)
print("first occurance of 3 is:", res)
# getting the index of 3 after 4th index
res= tup_1.index(3, 4)
print("first occurance of 3 after 4th index is:", res)

Output:

first occurance of 3 is: 3
first occurance of 3 after 4th index is: 5

Tuple Membership Test:
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

Code:

#Python progrm to show how to perform membership test for tuples.
#creating a tuple
tup_=("orange", "apple", "banana", "apple", "orange", "papaya")
#in operator
print('apple' in tup_)
print('tomato' in tup_)
#not in operator
print('potato' not in tup_)
print('orange' not in tup_)

Output:

True
False
True
False

Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code:

#Python progrm to show how to iterate over tuple elements
#creating a tuple
tup_=("orange", "apple", "banana", "apple", "orange", "papaya")
#iterating over tuple elements using a for loop
for item in tup_:
    print(item)

Output:

orange
apple
banana
apple
orange
papaya

Changing a Tuple:
Tuples, instead of records, are permanent articles.
This suggests that once the elements of a Tuple have been defined, we cannot change them. However the nested elements can be altered if the element itself is a chargeable data type like a list.

Multiple values can be assigned to a Tuple through reassignment.

Code:

#Python progrm to show that Python tuples are immutable objects.
#creating a tuple
tup_=("orange", "apple", "banana", "apple", [1, 2, 3, 4])
#trying to change the element at index 2
try:
    tup_[2] = "items"
    print(tup_)
except Exception as e:
    print(e)
#but inside a tuple, we can change elements of a mutable object
tup_[-1][2] = 10
print(tup_)
#changing the whole tuple
tup_=(
"orange", "apple")
print(tup_)

Output:

'tuple' object doesn't support item assignment
('orange', 'apple', 'banana', 'apple', [1, 2, 3, 4])
('orange', 'apple')

The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This is already demonstrated above.
The aftereffects of tasks + and * are new tuples.

Code:

#Python progrm to show how to concatenate tuples.
#creating a tuple
tup_=("orange", "apple", "banana", "apple")
#adding a tuple to the tup_
print(tup_ + (1, 2, 3))

Output:

('orange', 'apple', 'banana', 'apple', 1, 2, 3)

Tuples have the following advantages over lists:
  • Tuples take less time than lists do.
  • Due to tuples, the code is protected from accidental modifications. It is desirable to store non-changing information in "tuples" instead of "records" if a program expects it.
  • A tuple can be used as a dictionary key if it contains immutable values like strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys because they are mutable. 

No comments:

Post a Comment

Python: Functions