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:-

Show Output

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

Show Output

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

Show Output

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

Close Menu