Search⌘ K
AI Features

Tuples

Explore the concept of tuples in Python 3 as immutable ordered collections. Learn to define tuples, access elements using indices, and use slicing. Understand why tuples are faster than lists and how to use them to protect data integrity. Discover how tuples work in boolean contexts and how to perform multiple assignments with tuples effectively.

A tuple is an immutable list. A tuple can not be changed in any way once it is created.

Python 3.5
a_tuple = ("a", "b", "mpilgrim", "z", "example") #①
print (a_tuple)
#('a', 'b', 'mpilgrim', 'z', 'example')
print (a_tuple[0] ) #②
#a
print (a_tuple[-1]) #③
#example
print (a_tuple[1:3] ) #④
#('b', 'mpilgrim')

① A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.

② The elements of a tuple have a defined order, just like a list. Tuple indices are zero-based, just like a list, so the first element of a non-empty tuple is always a_tuple[0].

③ Negative indices count from the end of the tuple, just like a list.

④ Slicing works too, just like a list. When you slice a list, you get a new list; when you slice a tuple, you get a new tuple.

The major difference between tuples and lists is that tuples can not be changed. In technical terms, tuples are immutable. In practical terms, they have no methods that would allow you to change them. Lists have methods like append(), extend(), insert(), remove(), and ...