Search This Blog

Wednesday, 15 December 2021

Tuples in Python

 

Python Tuple

free simple website templates

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses (), whereas lists use square [] brackets.

Tuple is similar to list. Only the difference is that list is enclosed between square bracket, tuple between parenthesis and List has mutable objects whereas Tuple has immutable objects.


tuple=()  #empty tuple

Example : Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these comma-separated values between parentheses also.

t1=('a','b',1,2,3.14,"ApkZube")
t2="a", "b", "c", "d"

#tuple contain other list and tuple
t3 =(1,2,3,['a','b','c'],('z',26))

print(t1)
print(t2)
print(t3)

output of above example  :

('a', 'b', 1, 2, 3.14, 'ApkZube')
('a', 'b', 'c', 'd')
(1, 2, 3, ['a', 'b', 'c'], ('z', 26))

For a single valued tuple, there must be a comma at the end of the value. 

t1=(5,)
print(t1)

output of above example  :

(5,)

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For example - 

tuple[index]

slice operator syntax :

tuple[start : stop : step]

by default step is +1

t=(3,7,4,2)

print(t[2])
print(t[1:3])
print(t[-4:-2])
print(t[-1 :  : -1])  #start from -1 and step =-1 so its basicly return reverse tuple

output of above example  :

4
(7, 4)
(3, 7)
(2, 4, 7, 3)

interation tuple using for loop is same as list : 

t=("apkzube",'xyz',1,2,3)
for x in t:
    print(x)

ouput :

apkzube
xyz
1
2
3

Tuple Operations

Python allows us to perform various operations on the tuple. Following are the common tuple operations.

  • Adding Tuples

Tuple can be added by using the concatenation operator(+) to join two tuples this create new tuple.

Note: The new sequence formed is a new Tuple.

Example :

t1=(1,2,3)
t2=('x','y','z')
t3=t1+t2
print(t3)

output of above example  :

(1, 2, 3, 'x', 'y', 'z')
  • Replicating Tuple

Replicating means repeating. It can be performed by using '*' operator by a specific number of time.

Example :

t1=(1,2,3)
t2=('x','y','z')
print(t1*2)
print(t2*3)

output of above example  :

(1, 2, 3, 1, 2, 3)
('x', 'y', 'z', 'x', 'y', 'z', 'x', 'y', 'z')
  • Updating Tuples

Tuples are immutable, which means you cannot update or change the values of tuple elements. You are able to take portions of the existing tuples to create new tuples as the following example - 

t1 = (1, 2,3)
t2 = ('abc', 'xyz')

# Following action is not valid for tuples
# t1[0] = 4;
# So let's create a new tuple as follows
t3 = t1 + t2

print (t3)

output of above example  :

(1, 2, 3, 'abc', 'xyz')
  • Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.To explicitly remove an entire tuple, just use the del statement. For example −

t = ('apkZube', 'python', 1, 2);

print (t)
del t;
print ("After deleting t :")
print (t)

output of above example  :

('apkZube', 'python', 1, 2)
After deleting t :
Traceback (most recent call last):
  File "main.py", line 15, in
    print (t)
NameError: name 't' is not defined

Built-in Tuple Functions

funDescription
cmp(t1, t2)Compares elements of both tuples (py 2.x).
In Python 3 the cmp built-in function was removed
len(tuple)Gives the total length of the tuple.
max(tuple)Returns item from the tuple with max value.
min(tuple)Returns item from the tuple with min value.
tuple(seq)Converts a sequence into tuple.
  • len(tuple) - The len() method returns the number of elements in the tuple.

Example : 

t1= (1,2,3,4,5)
t2 = ('x','y','z',[1,2],3)
print(len(t1))
print(len(t2))

output of above example  :

5
5
  • max(tuple) - The max() method returns the elements from the tuple with maximum value. Type of element should be same otherwise complier throw TypeError.

Example :

t1= (1,2,3,4,5)
t2 = ('x','y','z')
print(max(t1))
print(max(t2))

output of above example  :

5
z
  • min(tuple) - The min() method returns the elements from the tuple with minimum value. Type of element should be same otherwise complier throw TypeError.

Example :

t1= (1,2,3,4,5)
t2 = ('x','y','z')
print(min(t1))
print(min(t2))

output of above example  :

1
x
  • tuple(seq) - The tuple() method converts a list of items into tuples. 

Example :

s="apkzube"
t1=tuple(s)
list=[1,2,3]
t2=tuple(list)

print(t1)
print(t2)

output of above example  :

('a', 'p', 'k', 'z', 'u', 'b', 'e')
(1, 2, 3)

Why should wee use Tuple? (Advantages of Tuple)

  • Processing of Tuples are faster than Lists. 
  • It makes the data safe as Tuples are immutable and hence cannot be changed.
  •   Tuples are used for string formatting.

No comments:

Post a Comment

how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...