tuple: Tuples in Python

Introduction

A tuple in Python is:

Roughly speaking, a tuple is a list that cannot be changed. That is, a tuple has read-only rights. This can be a protection against accidental changes.

Create an empty tuple:

t = tuple() print(t)

()

A tuple can consist of a single element:

# This is a string s = ("b") print(type(s)) print(s) # This is a tuple t = ("b",) print(type(t)) print(t)

Pay attention to the comma

<class 'str'> b <class 'tuple'> ('b',)

A tuple from a list:

list_cities = ["benalmadena", "cordoba", "fuengirola", "malaga", "torremolinos"] tuple_cities = tuple(list_cities) print(type(list_cities)) print(type(tuple_cities)) print(tuple_cities)

<class 'list'> <class 'tuple'> ('benalmadena', 'cordoba', 'fuengirola', 'malaga', 'torremolinos')

The objects in a tuple can be accessed, just like the objects of a list, by their ordinal number:

# By index print(tuple_cities[0])

benalmadena

Immutability

Since a tuple is immutable, a new value cannot be assigned:

tuple_cities[1] = "barcelona"

Traceback (most recent call last): File "tuple_ex.py", line 18, in <module> tuple_cities[1] = "barcelona" TypeError: 'tuple' object does not support item assignment

TypeError can be handled with except

try: tuple_cities[1] = "barcelona" except TypeError: print("Can't change tuple")

Can't change tuple

sorted()

The sorted function sorts the elements of a tuple in ascending order and returns a new list with the sorted elements:

tuple_cities = ("cordoba", "fuengirola", "malaga", "torremolinos", "benalmadena") sorted_list_cities = sorted(tuple_cities) print(type(sorted_list_cities)) print(sorted_list_cities)

<class 'list'> ['benalmadena', 'cordoba', 'fuengirola', 'malaga', 'torremolinos']

Article author: Andrei Olegovich

Banner image