What is a Python Tuple? Basic Usage and Differences from Lists

Python has several data types for managing collections of data. Among them, the tuple is very similar to a list, but there is one decisive difference. That is, tuples are “immutable” (unchangeable), meaning their contents cannot be changed, added to, or deleted once created.

This article explains how to create tuples and how they differ from lists.


目次

1. Creating Tuples with () (Parentheses)

The most basic way to create a tuple is to enclose multiple elements in parentheses () and separate them with commas ,.

# Tuple with multiple elements
server_settings = ("192.168.0.1", 8080, "production")

print(server_settings)
print(f"Type: {type(server_settings)}")

Output:

('192.168.0.1', 8080, 'production')
Type: <class 'tuple'>

Creating an Empty Tuple

You can create an empty tuple using just ().

empty_tuple = ()
print(f"Empty Tuple: {empty_tuple}")

Note: Tuple with Only One Element

This is one of the most important points when creating tuples. If you want to create a tuple with only a single element, you must include a comma (,) at the end.

# 1. Bad Example: This becomes a string 'admin', not a tuple
user_role_bad = ("admin")
print(f"Bad Example Type: {type(user_role_bad)}")

# 2. Good Example: Add a comma at the end
user_role_good = ("admin",) # The comma (,) is crucial
print(f"Good Example Type: {type(user_role_good)}")

Output:

Bad Example Type: <class 'str'>
Good Example Type: <class 'tuple'>

Since () is also used for mathematical precedence, ("admin") is interpreted simply as the string "admin". By writing ("admin",), Python recognizes it as a tuple.


2. Omitting Parentheses

Grammatically, you can create a tuple by simply listing values separated by commas, without ().

# Tuple without parentheses (often used in multiple assignment)
color_code = 255, 165, 0 # Same meaning as (255, 165, 0)

print(color_code)
print(f"Type: {type(color_code)}")

Output:

(255, 165, 0)
Type: <class 'tuple'>

When a function seems to return multiple values (e.g., return x, y), it is actually returning a tuple.


3. Converting with the tuple() Constructor

You can use the tuple() constructor to convert other “iterables” (like lists or range()) into tuples.

# Convert a list to a tuple
user_list = ["admin", "editor", "guest"]
user_tuple = tuple(user_list)

print(f"Original List: {user_list}")
print(f"Converted Tuple: {user_tuple}")

Output:

Original List: ['admin', 'editor', 'guest']
Converted Tuple: ('admin', 'editor', 'guest')

4. Tuple Property: Immutable (Unchangeable)

The biggest difference between tuples and lists is that tuples cannot be modified once created. Operations like changing, adding, or deleting elements, which work for lists, will cause an error for tuples.

server_settings = ("192.168.0.1", 8080, "production")

# Error when trying to change an element
# server_settings[1] = 9090
# TypeError: 'tuple' object does not support item assignment

# Error when trying to add an element
# server_settings.append("new_value")
# AttributeError: 'tuple' object has no attribute 'append'

Why Use Tuples?

Although being unchangeable might seem inconvenient, it offers several benefits:

  1. Data Protection: Good for storing data you don’t want changed accidentally (e.g., configuration values, coordinates).
  2. Dictionary Keys: Since tuples are immutable, they can be used as keys in a dictionary (lists cannot be keys).
  3. Performance: Generally, tuples are slightly faster and consume less memory than lists.

Summary

  • Create tuples with () like (1, 2, 3).
  • For a single element, a comma is required: (1,).
  • Parentheses can be omitted: 1, 2, 3.
  • Convert from a list using tuple(list).
  • The main feature is “Immutable”: you cannot change the contents once created.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次