{article Dive into Python}{title} {text}{/article}

A tuple is an immutable list. A tuple can not be changed in any way once it is created, tuples are immutable and tuples use ( ) parentheses and lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also.

Tuples may be created directly or converted from lists. Generally, tuples are enclosed in parentheses.

These are the same as for lists except that we may not assign to indices or slices, and there is no "append" operator.


Defining a tuple

  1. tuple = ("a", "b", "mpilgrim", "z", "example")
  2. tuple[0]
  3. tuple[-1]
  4. tuple[1:3]
  1. A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.

  2. The elements of a tuple have a defined order, just like a list. Tuples indices are zero−based, just like a list, so the first element of a non−empty tuple is always t[0].

  3. Negative indices count from the end of the tuple, just as with a list.

  4. Slicing works too, just like a list. Note that when you slice a list, you get a new list; when you slice a tuple, you get a new tuple.

tuple = ("a", "b", "mpilgrim", "z", "example")
tuple
('a', 'b', 'mpilgrim', 'z', 'example')
tuple[0]
'a'
tuple[-1]
'example'
tuple[1:3]
('b', 'mpilgrim')


Tuples Have No Methods

These are the same as for lists except that we may not assign to indices or slices, and there is no "append" operator.

t = ("a", "b", "mpilgrim", "z", "example")

  1. t.append("new")

  2. t.remove("z")

  3. t.index("example")

  4. "z" in t

  1. You can't add elements to a tuple. Tuples have no append or extend method.

  2. You can't remove elements from a tuple. Tuples have no remove or pop method.

  3. You can't find elements in a tuple. Tuples have no index method.

  4. You can, however, use in to see if an element exists in the tuple.

Tuples can be converted into lists, and vice−versa.
The built−in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list.
In effect, tuple freezes a list, and list thaws a tuple.