Member-only story
3 Things You May Not Know About Python Tuples
Getting better to use tuples
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)
>>>…