Welcome

sampleqa.in tutorials, python tutorial

Python tutorial


Python Tuple Methods

methoddescription
countreturns number of occurances of a given element
indexfirst index of a given element, otherwise Exception is thrown

Creating a tuple

     Tuple can be created using following methods

		>>>t=()   --empty tuple
		>>>t=(1,2,3,1,2,3,3,3,3,33)   --tuple with 10 elements
		>>>t=tuple("programmer") --tuple() built-in function with iterable object,string
		>>>t=tuple( (1,2,3,1,2,3,3,3,3,33)   )  --tuple accepting another tuple
	

tuple count method

    count method returns number of occurances of a given element

Tuple created with 10 elements, some elements are repeated.
counting occurance of element 1, element 1 occured 2 times
counting occurance of element 3, element 3 occured 5 times
counting occurance of element 333, element 333 occured 0 times,because 333 element doesnt exists, so returns 0

count function is used to
1.find repeated elements .
2. It is used to find presence of an element

		>>>t=(1,2,3,1,2,3,3,3,3,33) 
		>>>
		>>>t.count(1)
		2
		>>>t.count(3)
		5
		>>>
		>>>t.count(333)
		0
		
	

tuple index method

    index method returns first index of a given element, otherwise ValueError Exception is thrown
element index starts from 0 to N-1.

		>>>t=(1,2,3,1,2,3,3,3,3,33) 
		>>>
		>>>t.index(1)     --  1 is located in multiple positions, but first index returned, i.e 0
		0   	
		
		>>>t.index(33)    --  33 located in 9th position
		9
		
		>>>t.index(333)   -- 333  doesnot exists in the tuple, so throws ValueError: tuple.index(x): x not in tuple
	
difference between count & index is, element not found index throws Exception,whereas count returns 0

ADS