Similar to lists, tuples are sequences of arbitrary items. Unlike lists, tuples are immutable, meaning you can’t add, delete, or change items after the tuple is defined. So, a tuple is similar to a constant list.
The syntax to make tuples is a little inconsistent, as we’ll demonstrate in the examples that follow.
Let’s begin by making an empty tuple using ():
>>> empty_tuple = () >>> empty_tuple ()
To make a tuple with one or more elements, follow each element with a comma. This
works for one-element tuples:
>>> one_marx = 'Groucho', >>> one_marx ('Groucho',)
If you have more than one element, follow all but the last one with a comma:
>>> marx_tuple = 'Groucho', 'Chico', 'Harpo' >>> marx_tuple ('Groucho', 'Chico', 'Harpo')
Python includes parentheses when echoing a tuple. You don’t need them, it’s the trailing commas that really define a tuple, but using parentheses doesn’t hurt 😃. You can use them to enclose the values, which helps to make the tuple more visible:
>>> marx_tuple = ('Groucho', 'Chico', 'Harpo') >>> marx_tuple ('Groucho', 'Chico', 'Harpo')
Tuples let you assign multiple variables at once:
>>> marx_tuple = ('Groucho', 'Chico', 'Harpo') >>> a, b, c = marx_tuple >>> a 'Groucho' >>> b 'Chico' >>> c 'Harpo'
This is sometimes called tuple unpacking.
You can use tuples to exchange values in one statement without using a temporary variable:
>>> password = 'swordfish' >>> icecream = 'tuttifrutti' >>> password, icecream = icecream, password >>> password 'tuttifrutti' >>> icecream 'swordfish' >>>
The tuple() conversion function makes tuples from other things:
>>> marx_list = ['Groucho', 'Chico', 'Harpo'] >>> tuple(marx_list) ('Groucho', 'Chico', 'Harpo')
You can often use tuples in place of lists, but they have many fewer functions.
There is no
insert(), and so on, because they can’t be modified after creation.
Thanks for reading ♥️🔥.