[go: up one dir, main page]

0% found this document useful (0 votes)
11 views8 pages

Pb-U7.4 Tuple

This document provides a comprehensive overview of tuples in Python, detailing their characteristics, creation, initialization, and various operations such as indexing, slicing, and membership testing. It explains the immutable nature of tuples, how to access their elements, and the built-in functions available for tuple manipulation. Additionally, it covers tuple operators for concatenation and replication, as well as methods for counting and sorting elements within a tuple.

Uploaded by

rvsnhis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views8 pages

Pb-U7.4 Tuple

This document provides a comprehensive overview of tuples in Python, detailing their characteristics, creation, initialization, and various operations such as indexing, slicing, and membership testing. It explains the immutable nature of tuples, how to access their elements, and the built-in functions available for tuple manipulation. Additionally, it covers tuple operators for concatenation and replication, as well as methods for counting and sorting elements within a tuple.

Uploaded by

rvsnhis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit 3: Advance Python Vision 2 Win

Tuples
 Introduction :
o TUPLE is a collection of items and each item has its own index value.
o Tuple is a standard data type of Python. It is a sequence which can store values of any kind.
o Tuple is represented by round brackets / parentheses “ ( ) “
o Tuple is an immutable data type which means we cannot change any value of tuple.
o In Python Tuple is a sequence of items and each item can be individually access using index.
From beginning the first item in Tuple is at index 0 and last will be at len-1. From backward
direction last item will be at index -1 and first item will be at –len.

Forward indexing
0 1 2 3 4 5 6 7 8 9 Positive Index

70 10
10 20 30 40 50 60 80 90 Values
0
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Negative Index

Backward indexing
 Creating & Initializing Tuple:
 Creating a tuple
 Tuples are enclosed in parentheses () and each item is separated by a comma.
 Syntax: TupleName = ( )
o Creating tuple from existing sequences (i.e. Using tuple() function…
 Syntax: TupleName = tuple(sequence)
Code: Output:
>>>Mytuple = tuple(‘Hello’) (‘H’,’e’,’l’,’l’,’o’)
>>>Mytuple
Code: Output:
>>>Mytuple = [‘H’,’e’,’l’,’l’,’o’] (‘H’,’e’,’l’,’l’,’o’)
>>>Mytuple1 = tuple(Mytuple)
>>>Mytuple1

o Creating tuple from existing sequences (i.e. Using input() function…)


 We can also create tuple of single characters or single digits through input() function.
 Syntax: TupleName = tuple(input(“Statements”))
Code: Output:
>>>Mytuple = tuple(input(“Enter Tuple Elements :”)) (‘1’,’2’,’3’,’4’,’5’)
Enter Tuple Elements : 12345
>>>Mytuple
Note: when we input values as numbers to a tuple even then numbers automatically converted
to Tuple.

Artificial Intelligence 1 Class 10


Unit 3: Advance Python Vision 2 Win

 Initializing a tuple
 Passing value in tuple while declaring tuple is initializing of a tuple.
 Syntax: TupleName = ( value1, value2,…..)

o TUPLE can also be created Using Initialization methods…


Code: Output:
>>>Mytuple = (‘H’,’e’,’l’,’l’,’o’) (‘H’,’e’,’l’,’l’,’o’)
>>>Mytuple
o Ex:
 Tuple=()
 Tuple=(1,2)
 Tuple=(1,2,13.34,16.24)
 Tuple=(1,2,(1,2,3,4))
 Tuple=(1,2,[1,2,3,4])

 Accessing Tuple Elements:


o Tuple is a sequence like a string. Tuple also has index of each of its element. Values can be
accessed like string.
o In Python, individual item of a Tuple can be accessed by using the method of Indexing.
Index is positive address references to access item from the forward of the Tuple & allows
negative address references to access item from the back of the Tuple,
o While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.
o Ex: n=( 10,20,30,40,50,60,70,80,90,100)

0 1 2 3 4 5 6 7 8 9
10 20 30 40 50 60 70 80 90 100
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Code: Output:
>>> n=( 10,20,30,40,50,60,70,80,90,100)
>>>n[1] 20
>>>n[5] 60
>>>n[-3] 80
>>>n[15] Index Error
>>>n[3:8] (40,50,60,70)

 Traversal /Iterating of a tuple


o Traversal of a tuple means to access and process each and every element of that tuple.
o Process of accessing each and every element of a tuple for the purpose of display or for some
other purpose is called Traversal.

Artificial Intelligence 2 Class 10


Unit 3: Advance Python Vision 2 Win

o It means accessing the individual element of tuple i.e. from first element to last element.
o Every element in tuple is at different index position i.e. from 0 to size-1.
o Traversal of a tuple is very simple with for loop.
Code: Output:
tpl = (‘I’,’N’,’D’,’I’,’A’) I-N-D-I-A-
for i in tpl :
print(i,end=’-‘)
Code: I
tpl = (‘I’,’N’,’D’,’I’,’A’) N
for i in tpl: D
print(i) I
A
Code: Output:
tpl = (‘I’,’N’,’D’,’I’,’A’) Index 0 and the element at index -5 is I
l=len(lst) Index 1 and the element at index -4 is
for i in range(0,l): N
print(“Index “,i,” and the element at index“, Index 2 and the element at index -3 is
(i-l),”is”, tpl (i)) D
Index 3 and the element at index -2 is I
Index 4 and the element at index -1 is
A

 Tuple operators
o There are many operations that can be performed with Tuple which makes it one of the most
used data types in Python.
o Two basic operators + and * are allowed
 + is used for concatenation (joining)
 * Is used for replication (repetition)

o Tuple Concatenation Operator (Joining) (+):


 Joining of two or more Tuple into a single one is called Concatenation.

 Syntax:
<Tuple1> + <Tuple2>

 Example:
(10,20,30) + (40,50)  (10,20,30,40,50)
(‘I’) + (“Love”) + (“India”)  (‘I’,“Love”,“India”)

Code: Output:
>>> T1=( 10,20,30,40,50)
>>>T2=(60,70,80,90,100) (10,20,30,40,50,60,70,80,90,100)
>>>T3 = T1 + T2
>>>T3
 Note: you can only add tuple with another tuple not with int, float, complex, or string
type.

Artificial Intelligence 3 Class 10


Unit 3: Advance Python Vision 2 Win

(10,20,30) + 5  Invalid

o Tuple Replication Operator (Repetition) (*):


 The * operator can be used to repeat the Tuple for a given number of times.
 * needs two types of operands, i.e. a Tuple and a number.
 Syntax:
<Tuple> * <Number>
 Example:
(10,20,30) * 3  (10,20,30,10,20,30,10,20,30)
(‘I’,“Love”,“India”) *2  (‘I’,“Love”,“India”,‘I’,“Love”,“India”)
 Note: you cannot multiply tuple and tuple using *. Only number*tuple or tuple*number is
allowed.
(10,20,30) * (40,50,60)  Invalid

 Membership operators (in & not in)


o in operator: Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
o not in operator: Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise.
 Syntax:
<element> in <tuple>
<element> not in <tuple>
 Example:
20 in (10,20,30,40)  True
50 in (10,20,30,40)  False
10 not in (10,20,30,40)  False
“Ind” in (“Ind”,US)  True
“e” in (‘K’,’e’,’n’,’s’,’r’,’i’)  True
“z” in (‘K’,’e’,’n’,’s’,’r’,’i’)  False

 Tuple Slicing
o As we know slice means “part of”, so slicing is a process of extracting part of tuple.
o OR Slicing is a part of a tuple containing some continuous character from the tuple.
o The tuple are sliced using a range of indices (Tuple characters have their unique index
position from 0 to length-1 and -1 to –length(backward)).

o Syntax: seq = tuple ( start : stop ) OR seq = tuple ( start : stop : step )

o Example1: Tpl1 = ( 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 )
Tpl1[: ] / Tpl1[ : :] / Tpl1  ( 10, 20, 30, 40, 50, 60, 70, 80, 90 )
Tpl1[ 2 : 5 ]  ( 30, 40, 50 )
Tpl1[ 3 : -3 ]  ( 40, 50, 60 )
Tpl1[ 0 : 10 : 2 ]  ( 10, 30, 50, 70, 90 )
Tpl1[ : : 3 ]  ( 10, 40, 70 )
Tpl1[ : : -1 ]  ( 90, 80, 70, 60, 50, 40, 30, 20, 10 )

Artificial Intelligence 4 Class 10


Unit 3: Advance Python Vision 2 Win

Tpl1[ : : -2 ]  ( 90, 70, 50, 30, 10 )


Tpl1[ -4 : -1 ]  ( 60, 70, 80 )
Tpl1[ : : 3 ]  ( 10, 40, 70 )
Tpl1 [ 4 ]  ( 50 )
Tpl1[ 15 ]  IndexError: tuple index out of range

o Example2: Tpl1 = ('I','N','D','I','A')


Tpl1( 0 : 3 )  ('I', 'N', 'D')
Tpl 1( 3 : )  ('I', 'A')
Tpl 1(:)  ('I', 'N', 'D', 'I', 'A')

 Use of slicing for tuple Modification


Code: Output:
T =("One","Two","Three")
print(T) ('One', 'Two', 'Three')

T[0:2]=(0,1) TypeError: 'tuple' object does


print(T) not support item assignment.
T[2:0]= "604" TypeError: 'tuple' object does
print(T) not support item assignment
Bcoz Tuple Immutable

 TUPLE FUNCTIONS AND METHODS


o Python offers many built-in functions for Tuple manipulation.
o Syntax: <Tuple_Object> . <functionName> ()

 index(substring) :
o This function returns index position of substring.
o If substring not it returns error ‘substring not found’
o OR This function is used to get the index of first matched item from the tuple. It returns
index value of item to search
o Syntax : <Tuple_Object>.index(substring) :
o Example:

Code: Output:
Tpl=(10,20,30,40,50,60,70,80,90,100) 4
print(Tpl. index (50))
Code: Output:
Tpl=(10,20,30,40,50,60,70,80,90,100) ValueError: tuple.index(x): x
print(Tpl. index (200)) not in tuple.

o Note: if we pass any element which is not in the tuple then index function will return an
error.

Artificial Intelligence 5 Class 10


Unit 3: Advance Python Vision 2 Win

 len(string) :
o This function returns the number of characters in any tuple including spaces.
o Syntax : len( <Tuple_Object> )
o Example:

Code: Output:
Tpl=(10,20,30,40,50,60,70,80,90,100) 10
print(len(Tpl))
Code: Output:
Tpl=(‘I’,’N’,’D’,’I’,’A’) 5
print(len(Tpl))

 Deletion of Tuple elements Using del():


o As we know that tuple is of immutable type, it is not possible to delete an individual element
of a tuple. With del() function, it is possible to delete a complete tuple.
o Direct deletion of tuple element is not possible but shifting of required content after discard
of unwanted content to another tuple.
o The del statement of python is used to delete elements and objects but as you know that
tuples are immutable, which also means that individual elements of tuples cannot be deleted.
o Syntax : del <Tuple>

o Example:

Code: Output:
Tpl = ( 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 )
del Tpl(2) TypeError: 'tuple' object doesn't
print(Tpl) support item deletion.
Error shown because deletion of a
single element is also possible
Tpl = ( 10, 20, 80, 90) Deletes all elements…
del Tpl NameError: name 'Tpl' is not
print(Tpl) defined
Complete tuple has been deleted. Now
error shown on printing of tuple.

 count()
o This function returns the count of the item that you passed as an argument. If the given item is
not in the tuple, it returns zero. OR The count() method returns the number of times element
appears in the tuple.
o Syntax : < Tuple_object >.count(element)
Here, element - the element to be counted.

o Example: Tpl=(10, 20, 30, 10, 50, 10, 60, 10, 10)

Code: Output:
5

Artificial Intelligence 6 Class 10


Unit 3: Advance Python Vision 2 Win

print(Tpl.count(10))
print(Tpl.count(20)) 1
print(Tpl.count(100)) 0

 sorted()
o This function sorts the items of the tuple, by default increasing order. This is done «in place»
i.e. It does not create new tuple.
o Syntax : <Tuple1>.sorted(Tuple2) // By default increasing order (Ascending order)

Code: Output:
T1= (10, 50, 40, 30, 20)
print(T1) (10, 50, 40, 30, 20)
T2.sorted(T1)
print(T2) (10, 20, 30, 40, 50)

o Note: If a tuple contains a complex number, sort will not work.

 min()
o Returns item from the tuple with min value.can be done via list
o Syntax : min(Tuple_Seq)
o Example:
Code: Output:
T=(10, 20, 30, 40, 30, 50, 30) 10
print(min(T))

 max()
o Returns item from the tuple with max value.can be done via list.
o Syntax : max(Tuple_Seq)
o Example:
Code: Output:
T=(10, 20, 30, 40, 30, 50, 30) 50
print(max(T))

 tuple()
o Converts a list into tuple.
o Syntax : tuple(Seq)
o Example:
Code: Output:
T=[10, 20, 30, 10, 50, 10, 60, 10] (10, 20, 30, 10, 50, 10, 60,10)
T1=tuple(T)
print(T1)
Str=”INDIA” ('I', 'N', 'D', 'I', 'A')

Artificial Intelligence 7 Class 10


Unit 3: Advance Python Vision 2 Win

s=tuple(Str)
print(s)

 sum()
o sum of tuple elements can be done via list
o Syntax : sum(list(Seq))
o Example:
Code: Output:
T=(10, 20, 30]) Sum= 60
T1= sum(list(T)
print(“Sum =”,T1)

Artificial Intelligence 8 Class 10

You might also like