Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Are Tuples Immutable Lists?

Python also provides tuples, which resemble lists. Write a tuple as follows.

variable = (value1, value2, ...)

To retrieve a value, specify an index inside square brackets, as with a list. For example, write str[0].

What is the difference between a list and a tuple? Tuple values cannot be changed. A tuple behaves like a constant rather than a variable.

The ability to change values freely is important in programming. However, guaranteeing that values cannot change is also important. A list is unsuitable when unexpected updates would cause problems.

A tuple guarantees that its values will not change. Such containers may initially seem unnecessary, but they are useful when values must remain stable.

Other immutable containers include range. Objects that cannot be modified are called immutable objects. Objects that can be changed are called mutable objects. A list is a representative mutable container.

To use tuple values as a list later, convert them with a function.

Converting a Tuple to a List

variable = list(tuple)

Converting a List to a Tuple

variable = tuple(list)

The following example uses a tuple and a list.

tp = (0,1,2,3,4)
ls = list(tp)
for n in range(0,5):
    ls[n] = ls[n] * 2
for n in tp:
    print(ls[n])

The code creates the tuple tp, converts it into the list ls, and modifies the list values. Compare how ls and tp are used.