Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Tuples
  6. Tuple Methods

Tuple Methods

Length

Compares the items of two tuples

Syntax

len(tuple)

Example

>>> tuple1 = (3,2,4,1)
>>> len(tuple1)
4

Zip

  • Zips elements from two tuples into a list of tuples
  • Zip takes two or more sequences and zips into a list of tuples where each tuple contains one element from the sequence
  • When there are different number of elements in the tuples i.e., if the length of the tuples are not same then the resulting tuple after applying the zip function will have the length of shorter tuple

Syntax

zip(tuple1, tuple2)

Example

>>> tuple1 = (3,2,4,1)
>>> tuple2 = ("XXX","ABC","ZZZ","WWW")
>>> tuple3 = zip(tuple1,tuple2)
>>> list(tuple3)
[(3, 'XXX'), (2, 'ABC'), (4, 'ZZZ'), (1, 'WWW')]
>>> tuple1=(2,3)
>>> tuple2=("hello")
>>> tuple3=zip(tuple1,tuple2)
>>> list(tuple3)
[(2, 'h'), (3, 'e')]
>>> tuple2=("hello",)
>>> tuple3=zip(tuple1,tuple2)
>>> list(tuple3)
[(2, 'hello')]

Max

Returns the largest value among the elements in tuple

Syntax

max(tuple)

Example

>>> tuple1 = (0,1,-1,4,9,2)
>>> max(tuple1)
9

Min

Returns the smallest value among the elements in tuple

Syntax

min(tuple)

Example

>>> tuple1 = (0,1,-1,4,9,2)
>>> min(tuple1)
-1

Tuple

It converts a sequence (list, string) into tuple

Syntax

tuple(seq)

Example

>>> list1 = [3,4,"HI",4.0]
>>> tuple(list1)
(3, 4, 'HI', 4.0)
>>> str1 = "Python"
>>> tuple(str1)
('P', 'y', 't', 'h', 'o', 'n')

Index

Returns the index of the first matched item

Syntax

tuple.index(item)

Example

>>> tuple1 = (3,4,3,4,3,3,3)
>>> tuple1.index(3)
0

Count

Returns the count of the given element

Syntax

tuple.count(item)

Example

>>> tuple1 = (3,4,3,4,3,3,3)
>>> tuple1.count(3)
5

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments