TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Member-only story

3 Things You May Not Know About Python Tuples

Yong Cui
5 min readJun 29, 2022

--

Photo by Oscar Nilsson on Unsplash

Tuples are one important built-in data type in Python. Like lists, we often use tuples to save multiple objects as a data container. However, what makes them different from lists is their immutability — an immutable sequence of data. The following code snippet shows you some common usages for tuples.

response = (404, "Can't access website")response_code = response[0]
response_data = response[1]
assert response_code == 404
assert response_data == "Can't access website"

The above usages should be straightforward to you. We create a tuple object using a pair of parentheses, enclosing the elements. When we need to use individual items, we can use indexing.

Besides these basic usages, there are other usages that are less known. Let’s review them in this article.

1. Creating a tuple containing just one item

We mentioned that we use a pair of parentheses to create a tuple object. Typically, a tuple object contains two or more items, and we use commas to separate these items. What should we do if we want to create a one-item tuple? Is it (item)? Let’s try that:

>>> math_score = (95)
>>>…

--

--

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

Responses (1)