Python Tuples Tutorial

The tuple object (pronounced like toople or tuhple depending on who you’re asking for) is pretty much like a list that can’t be edited. In this article, I will present a tutorial on Python tuples.

Python Tuples

Python tuples are sequences, like lists, but they are immutable, like strings. Functionally, they are used to represent fixed collections of items as the components of a specific calendar date.

Syntactically, they are normally encoded in parentheses instead of square brackets and support arbitrary types, arbitrary nesting, and the usual sequence operations:

T = (1, 2, 3, 4) 
len(T)
4
T + (5, 6)
(1, 2, 3, 4, 5, 6)
T[0]
1

Tuples also have type-specific callable methods, but not as many as lists:

T.index(4)
3
T.count(4)
1

The main distinction between tuples and list is that they cannot be changed once created. In other words, they are immutable sequences:

T[0] = 2
TypeError: 'tuple' object does not support item assignment
T = (2,) + T[1:]
T
(2, 2, 3, 4)

Like lists and dictionaries, tuples also support mixed data types and nesting, but they don’t grow or shrink because they’re immutable:

T = 'spam', 3.0, [11, 22, 33]
T[1]
3.0
T[2][1]
22
T.append(4)
AttributeError: 'tuple' object has no attribute 'append'

When to Use Python Tuples?

So, why have a type that looks like a list, but supports fewer operations? Frankly, tuples aren’t usually used as often as lists in practice, but their immutability is the key point. If you pass a collection of objects around your program as a list, it can be edited anywhere; if you are using a tuple, it cannot. So we use tuples because it provides a kind of integrity constraint which is suitable for larger programs.

I hope you liked this article on a tutorial on Python tuples. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1535

Leave a Reply