Monday, June 19, 2023

Python Tuple

 

Tuple

Tuple is similar to a list.The difference between the two is that we cannot change the element of a tuple once it is assigned.But List element can be changable.

Advantage of 'Tuple' over 'List':

* Tuple is hetrogeneous(different data type).But List homogeneous(similar data type).

*Tuple are immutable .Tuple is faster than the list.So there is a slight performance boost.

*If you have data that doesn't change, implementing it as tuple will guarantee that it remains write - protected.

 

Creating a tuple

>>>tup1=()

>>>tup1=(3,5,7,9)

>>>tup1

(3,5,7,9)

>>>tup1=(1,2.5,"hello",10,3+2j)

>>>tup1

(1,2.5,"hello",10,3+2j)

>>>tup1[4]

(3+2j)

#If you can see tuple index only you can use [] square bracket, Not use  tuple () bracket

>>>tup1(2)

traceback (most recent call last):

file"<pysell#73>",line 1,in <module>

tup1(2)

type error:'tuple' object is not callable

>>>tup1[2]

'hello'

>>tup1[2][1]

'e'

>>>tup1=("hello",(2,4,6),("one","two","three"))

>>>tup1

('hello',(2,4,6),('one','two','three'))

>>>tup1[2][1]

'two'

#Wrong assignment

>>>tup1=103,GST,CHENNAI

traceback  (most recent call last):

file"<pyshell#79>",line 1,in<module>

tup1=103,GST,CHENNAI

NameError : name 'GST' is not defined

#tuple can be created without () - Tuple packing

>>> tup1=103,'GST','CHENNAI'

>>>tup1

(103,'GST','CHENNAI')

#Tuple packing and Unpacking

>>>x,y,z=tup1

>>>x

103

>>>y

'GST'

>>>z

'CHENNAI'

#It create string instead of tuple it will show in type string not show tuple

>>>tup1=("hello")

>>>type(tup1)

<class 'str'>

 

 

>>>tup1=tup("hai")

>>>tup1

('h','a','i')

>>>tup1=("hai")

>>>tup1

('hai')

>>>type(tup1)

<class 'tuple'>

>>>tup1="hai"

>>>tup1

'hai'

>>>type(tup1)

<class 'str'>

>>>tup1="hai"

>>>type(tup1)

<class 'tuple'>

>>> 

Accessing elements in a tuple

1.index

>>>tup1=("PYTHON PROGRAM")

>>>tup1

('PYTHON PROGRAM')

>>>type(tup1)

<class 'tuple'>

>>>print(tup1[4])

traceback (most recent call last)

file"<pyshell#150>",line 1,in <module>

>>>print(tup1[0])

PYTHON PROGRAM

>>>tup1=('P','Y','T','H','O','N')

>>>tup1

('P','Y','T','H','O','N')

>>>print(tup1[4])

O

>>>print(tup1[0])

P

>>>print(tup1[7])

traceback (most recent call last)

file"<pyshell#156>",line 1,in <module>

print(tup1[7])

index error:tuple index out of range

#Nested Tuple with 3X3 Matrix

>>>a=((1,2,3),(4,5,6),(7,8,9))

>>>print(a)

((1,2,3),(4,5,6),(7,8,9))

>>>print(a[1][1])

5

>>>print(a[2][2])

9

>>> 

2.Negative index

>>>tup1=('P','Y','T','H','O','N')

>>>tup1

('P','Y','T','H','O','N')

>>>tup1[-1]

'N'

>>>tup1[-5]

'Y'

>>>tup1[-6]

'P'

>>> 

 

3.Slicing

> > > tup1 = ('P','Y','T','H','O','N')

> > > tup1[2:2]

()

> > > tup1[2:3]

('T')                    

 > > > tup1[3:5]       #only  3rd and 4th

('H', 'O')

> > > tup1[2:]           #from 2nd to end

('T', 'H', 'O', 'N')

> > > tup1[:3]            #Begining to 3rd element

('P','Y','T')

> > > tup1[:-2]         #last 2nd position to first element

('P','Y','T','H')

> > > tup1[-3:]         #from 3rd element to last element

('H', 'O', 'N')

> > > tup1[:]             #only : shows all elements

('P', 'Y', 'T', 'H', 'O', 'N')

 > > >

Changing a Tuple

Tuple cannot be changed once it has been assigned.

#if you try to change the values in tuple it comes error

> > > tup1 = (10,'semester-1',(56,67,89))

> > > tup1[0] = 100

Trackback ( most recent call last)

         file " <pyshell#221 >", line 1, in  <module>

          tup1[0]  = 100

TypeError: 'tuple' object dose no support item assignment

#Tuple can be reassigned by again variable declaration

> > > tup1 = (100,'semester-1', (89,90,93))

#mutable element in the tuple can be changed

 > > > tup1 = (100,'semester-1', [89,90,93])

 > > >tup1[2][0] =99

> > > print(tup1)

(100,'semester-1',[99,90,93])

> > >

 Tuple concatenation Operator (+)

> > > tup1 = (30,40,50)

> > > tup2 = (10,15,6)

> > >  print (tup1 + tup2)

(30, 40, 50, 10, 15, 6)

> > > tup3 =tup1 + tup2

> > > tup3

(30, 40, 50, 10, 15, 6)

* Operator

> > > tup1 = (20 * 5)

> > > tup1

100

> > > tup 1   = ("hai"*5)

> > > tup 1

haihaihaihaihai

 

> > >

Deleting a Tuple

We cannot change the element in a tuple.We cannot delete or remove items from a tuple.

But deleting a entirely is possible using the keyword del.

> > > tup1 = ('P', 'Y', 'T', 'H', 'O', 'N')

> > > del tup1[2]

Trackback  (most recent call last )

      file "<pyshell#256>", line 1, in <module>

       del tup 1[2]

NameError: name 'tup 1' is not defined

> > >

Python Tuple Method

Method

Description

count (x)

Return the number of items that is equal to x

index(x)

Return index of first item that is equal to x

 

> > > tup1 = ('H','A','I','C','O','M','P','U','T','E','R')

> > > print(tup1.count('C'))      

1

> > > print(tup1.index('M'))    

5

> > >

> > >  tup1 = ('P','R','O','G','R','A','M','T','E','C','H','I','E')

 > > > print('C' in tup1)

True

> > > print ('X' in tup1)

False

> > >print ('X' not in tup1)

True

Other Tuple Operation

1.Tuple Membership Test

> > >tup1 = ('p','y','t','h','o','n')

> > >print('o' in tup1)

True

> > > print('b' intup 1)

False

> > > print ('g' not in tup1)

True  

2.lterating Through a Tuple

#example for access each element in a tuple

for name in ('Ram','kumar'):

     print("hello",name)

OUTPUT

Hello Ram

hello kumar

Built-in function with Tuple

all()

Return true if all elements of the list are true (or if the list is empty)

any()

Return  true if any elements of the list is true.if the list is empty,return false

enumerate()

Return an enumerate object.it contains the index and value of all the items of list as a tuple

len()

Return the length(the number of items)in the list

list()

Convert an iterable (tuple,string,set,dictionary)to a list

max()

Return the largest item in the list

min()

Return the smallest item in the list

sorted()

Return a new sorted list(does not sort the list itself)

sum()

Return the sum of all elements in the list      

tuple

Convert an iterable (list, string, set, dictionary) to a tuple.

 

creation , Repetition, concatenation

> > > t = (['xyz' 123],23, -103.4)

> > > t

 (['xyz' 123],23, -103.4)

> > > t * 2

(['xyz' 123],23, -103.4 , ['xyz' 123],23, -103.4)    

> > > t = t + ('free','easy')

> > > t

(['xyz' 123],23, -103.4 , 'free','easy')

Membership, slicing

> > > 23 in t

1

> > > 123 in t

0

> > > t[0][1]

123

> > > t[1:]

(23,-103.4,'free','easy')

Built - in Function

> > > str(t)

['xyz' 123],23, -103.4 'free','easy')

 > > > len(t)

5

> > > max(t)

'free'

> > > min(t)

-103.4

> > >cmp(t, (['xyz' 123],23, -103.4, 'free','easy')

0

> > > list(t)

[['xyz' 123],23, -103.4, 'free','easy']

Operators

> > > (4, 2) < (3, 5)       

0

> > > (2, 4) < (3, -1)      

1

> > > (2, 4) == (3, -1)      

0

> > > (2, 4) == (2, 4)       

1

Array - Efficient arrays of numeric values

from array import *

my_array = array('i',[1,2,3,4,5])

for i in my_array:

    print(i)

OUTPUT

1

2

3

4

5

                                                                                     

> > > my_array[1]

2

> > > my_array[2]

3

> > > my_array[0]

1

> > >my_array.append(6)

> > > my_array

array('i', [1, 2, 3, 4, 5, 6])

 

> > > my_array.insert(0,0)

> > > my_array                                                          

array('i', [0, 1, 2, 3, 4, 5, 6])

 

> > > my_extnd_array = array ('i', [7,8,9,10])

> > >my_array.extnd(my_extnd_array)

> > >my_array

array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

 

> > > c = [11, 12, 13]

> > >my_array.fromlist(c)

> > >my_array

array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

 

> > >my_array.remove(13)

> > >my_array

array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

 

> > >my_array.pop()

12

> > >my_array

array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

 

> > >my_array.index(5)

5

 

> > > my_array.reverse()

> > >my_array

array('i', [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

 

> > > my_array.buffer_info()

(33881712,12)

 

> > >my_array.count(11)

1

> > > my_char_array = array('c',['a','e','i','o','u'])

> > > my_char_array

array('c','aeiou')

> > > my_char_array.tostring()

'aeiou'

 

> > > c = my_array.tolist()

 >>>c

[11,10,9,8,7,6,5,4,3,2,1,0]

 

 


0 comments:

Post a Comment