Python Tuple

Python tuple is an immutable list which cannot be modified once it is created. In order to define a tuple, you assign a sequence of values to a variable. Different from a list,  all the tuple’s elements are enclosed in parentheses.

As you see in the code snippet above:

  • Like a list, tuple’s indices are zero-base therefore the first element of a tuple is tuple[0]
  • Negative indices starts from the end of the tuple.
  • Slicing like a list is applied to a tuple too so you get a new tuple when you slice a tuple.

A tuple is similar to a list except it has no method so you cannot add/remove elements from a tuple. A tuple is designed to be very useful in the following cases:

  • Because tuple is immutable so a tuple is faster than a list. If you intend to use a read-only list, you can use tuple instead.
  • A tuple can be used as a dictionary key because it is immutable. A list cannot be used as a dictionary key because a list is mutable.
  • A tuple is used to format string.

Converting a tuple into a list

A tuple can be converted into a list and vice verse.

To convert a tuple into a list you use function list() as follows:

A list also can be converted into a tuple using the built-in function tuple() as follows:

Defining a tuple with one element

It is notice that when you define a tuple with one element, you always need a comma at the end of the first element.

  • Was this tutorial helpful ?
  • YesNo