Tuples in Python

Tuples are immutable and they are very similar to lists. When creating tuples you have to use parentheses.

Example:

motorbikes = (“Honda”, “Yamaha”, “Suzuki”)

Tuples’ index can be accessed the same way you would access lists’ index.

print(motorbikes[1])

You can’t reassign a value in a tuple. It causes a TypeError.

motorbikes[0] = “Piaggio”

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Yamaha
Traceback (most recent call last):
  File "file.py", line 3, in 
    motorbikes[0] = "Piaggio"
TypeError: 'tuple' object does not support item assignment
ddn_ro@linux:~/Desktop$

Note:

  • Like lists and dictionaries, tuples can be nested within each other.
  • Tuples are faster than lists, but they cannot be changed.

Tuples can be created without the parentheses, by just separating the values with commas.

Example:

motorbikes = "Honda", "Yamaha", "Suzuki"
print(motorbikes[1])

If you want to create an empty tuple then you use an empty parenthesis pair.

empty_tpl = ()

Leave a Reply