DEV Community

loading...
Cover image for Python Tuples

Python Tuples

_zoka profile image Mahmoud Ibrahiam Updated on ・2 min read

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.

Create a Tuple by Using ()

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
()
Enter fullscreen mode Exit fullscreen mode

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',)
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Tuples let you assign multiple variables at once:

>>> marx_tuple = ('Groucho', 'Chico', 'Harpo')
>>> a, b, c = marx_tuple
>>> a
'Groucho'
>>> b
'Chico'
>>> c
'Harpo'
Enter fullscreen mode Exit fullscreen mode

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'
>>>
Enter fullscreen mode Exit fullscreen mode

The tuple() conversion function makes tuples from other things:

>>> marx_list = ['Groucho', 'Chico', 'Harpo']
>>> tuple(marx_list)
('Groucho', 'Chico', 'Harpo')
Enter fullscreen mode Exit fullscreen mode

You can often use tuples in place of lists, but they have many fewer functions.
There is no append(), insert(), and so on, because they can’t be modified after creation.
Thanks for reading ♥️🔥.

Discussion (2)

pic
Editor guide
Collapse
jadia profile image
Nitish Jadia

Sort, simple and informative post.

Collapse
_zoka profile image