In Python, Tuple is similar to list However, unlike a list, they are immutable i.e they cannot be changed.

Also, a tuple is similar to a range with only one exception. In tuple, every element is included but in range, the last element is excluded.

Constructing Tuples

Tuple is constructed with ( ) with elements separated by comma.

Let see with an example:-

#tuple
tup=(0,1,2,5)
print(tup)

#printing with for loop
for element in tup:
    print(element)

#Legth of a Tuple
print("Length: %d"%len(tup))

Output

(0, 1, 2, 5)

0
1
2
5

Length: 4

One tuple can also store more than one type of objects.

#mix types
tup = ('one', 1)
print(tup)

Output

('one', 1)

Indexing and slicing in tuples are similar to that of strings in python.

tup=(0,1,2,5)

#2nd from front
print(tup[2])

#3rd from back
print(tup[-3])

Output

2
1

[/toggle]

Basic Tuple Methods

Use: tuple_name.method_name()

  • count(x) – Count the how many ‘x’ is in the tuple.
  • index(x) – Returns the index of ‘x’.

Use: method_name(tuple_name)

  • min(tuple) – Returns minimum value item in the tuple.
  • max(tuple) – Returns maximum value item in the tuple.
  • len(tuple) – Length of the tuple.
  • cmp(tuple_1,tuple_2) – Compares length of the tuple.

Why to use Tuple?

Immutability.

If in your program, you are passing objects and doesn’t want it to change and neither its sequence then tuple is the best option to do so.

Leave a Reply

19 − 6 =