Tuple tuples in Python are described in detail

  • 2020-04-02 14:34:34
  • OfStack

A Tuple is an immutable list. Once you create a tuple, you can't change it in any way.

What a Tuple has in common with a list

A tuple is defined in the same way as a list, except that the entire set of elements is surrounded by parentheses instead of square brackets.
The elements of a Tuple are sorted in the same order as a list. A Tuples index starts at 0 as a list, so the first element of a non-empty tuple is always t[0].
A negative index counts from the tail of a tuple, just like a list.
Just like list, slice can also be used. Note that when you split a list, you get a new list; When you split a tuple, you get a new tuple.

A method that doesn't exist for a Tuple

You cannot add elements to a tuple. A Tuple has no append or extend methods.
You cannot remove elements from a tuple. Tuple has no remove or pop methods.
You cannot find elements in a tuple. A Tuple doesn't have an index method.
However, you can use in to see if an element exists in a tuple.

The advantage of using a Tuple

Tuples operate faster than lists. If you define a constant set of values, and the only thing you need to do with it is iterate over it, use a tuple instead of a list.
If you "write protect" data that doesn't need to be modified, you can make your code more secure. Using a tuple instead of a list is like having an implicit assert statement that this data is constant. If you have to change these values, you need to perform a tuple to list transformation.

Tuple versus list

A Tuple can be converted to a list, and vice versa. The built-in tuple function takes a list and returns a tuple with the same element. The list function takes a tuple and returns a list. In effect, a tuple freezes a list, and a list thaws a tuple.


Related articles: