DEV Community

Adam Lombard
Adam Lombard

Posted on • Edited on

10 6

Python: What is a tuple?

In Python, tuples are immutable data sequences. They are typically used to group related but heterogeneous values.

Say we have several pieces of information—in a variety of data types—that together describe a single work of art:

artist = "Louise Nevelson"
title = "Sky Gate, New York"
media = ["wood", "oil paint"]
completed = 1978
Enter fullscreen mode Exit fullscreen mode

It may be convenient to group these values together. Since the description of an artwork should never change during our program, an immutable tuple suits our needs perfectly:

artwork = (artist, title, media, completed)
Enter fullscreen mode Exit fullscreen mode

Elements in a tuple can be accessed by index:

>>> artwork[0]
'Louise Nevelson'
Enter fullscreen mode Exit fullscreen mode

But, since tuples are immutable, we cannot change elements by index:

>>> art_work[0] = "Ruth Asawa"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

For more information on tuples, see the Python docs.


Was this helpful? Did I save you some time?

🫖 Buy Me A Tea! ☕️


Learn more about Louise Nevelson and Ruth Asawa.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
bezirganyan profile image
Grigor Bezirganyan

Also, One more interesting usage of tuples is that you can use them as a key for dictionaries. (Dictionaries only accept immutable data types as key)

d = {}
d[(obj1, obj2, obj3)] = value
Collapse
 
miniscruff profile image
miniscruff

I highly recommend using named tuples when grouping.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay