Python Tutorial: Tuple Functions & Methods

Thursday, 13 August 2020

Tuple Functions & Methods


 

Function

Description

all()

Unlike any(), all() returns True only if all items have a Boolean value of True. Otherwise, it returns False.

Example :

>>> marks=(32,43,3)

>>> all(marks)

True

>>> marks=()

>>> all(marks)

True

>>> marks=(32,'43',3)

>>> all(marks)

True

>>> aTup=('1',1,True,'')

>>> all(aTup)

False

any()

If even one item in the tuple has a Boolean value of True, then this function returns True. Otherwise, it returns False.

Example :

>>> any(‘’, ‘32’, ‘’)

True

If even one item in the tuple has a Boolean value of True, then this function returns True. Otherwise, it returns False.

>>> any(‘’, 32, ‘’)

False   

The string ‘0’ does have a Boolean value of True. If it was rather the integer 0, it would’ve returned False.

len()

Like a list, a Python tuple is of a certain length. The len() function returns its length.

Example :

>>> Subject=('English','Physics','Chemistry','Chemistry','IP')

>>> len(Subject)

5

>>> salary=(30000,40000,25000)

>>> len(salary)

3

sorted()

Return a new sorted tuple. It returns a list after sorting.

Example :

>>> Subject=('English', 'Physics', 'Chemistry', 'Chemistry', 'IP')

>>> Subject

('English', 'Physics', 'Chemistry', 'Chemistry', 'IP') #output in tuple

>>> sorted(Subject)

['Chemistry', 'Chemistry', 'English', 'IP', 'Physics'] #output in list

>>> salary=(30000,40000,25000)

>>> salary

(30000, 40000, 25000) #output in tuple

>>> sorted(salary)

[25000, 30000, 40000] #output in list

tuple()

This function converts another construct into a Python tuple. Let’s look at some of those.

Example :

>>> Subject=['English', 'Physics', 'Chemistry', 'Chemistry', 'IP'] # value in list

>>> Subject

['English', 'Physics', 'Chemistry', 'Chemistry', 'IP']

>>> tuple(Subject) # converts list into tuple

('English', 'Physics', 'Chemistry', 'Chemistry', 'IP')

index()

Finds the first index of given item and returns the index.

Syntax:

tuple.index(value, start, end)

Example : 

Subject=('English','Physics','Chemistry','Chemistry','IP')

>>> Subject.index('Chemistry')

2

>>> Subject.index('CS')

Traceback (most recent call last):

  File "<pyshell#26>", line 1, in <module>

    Subject.index('CS')

ValueError: tuple.index(x): x not in tuple

count()

 

This method takes one argument and returns the number of times an item appears in the tuple.

>>> employee=('Sachin','Arun','Varun', 'Saumya','Arun')

>>> employee.count('Arun')

2

 

No comments:

Post a Comment