Major Python Data Types and Variable Properties (Mutable vs. Iterable)

Python is a “dynamically typed” language, meaning you do not need to explicitly declare the type of a variable. However, the data held by a variable has a clear “Type.” The data type defines what kind of data it is (integer, string, list, etc.) and what operations are possible.

This article explains Python’s major data types and two important properties for understanding them: Mutable/Immutable and Iterable.


目次

Major Python Data Types

Python data types can be broadly classified into “Types holding a single value” and “Collection types holding multiple values.”

1. Types Holding a Single Value

  • int (Integer): Handles positive and negative whole numbers.Pythonuser_count = 150 temperature = -5
  • float (Floating-point): Handles numbers with a decimal point.Pythonrate = 0.05 pi_value = 3.14159
  • bool (Boolean): Handles either True or False.Pythonis_active = True is_empty = False
  • NoneType (None): A special type representing “no value.” It only holds the value None.Pythonresult = None

2. Types Holding Multiple Values (Collections)

These types handle groups of data.

  • str (String): A sequence of characters. It has an order and is enclosed in " or '.Pythonapp_title = "Admin Panel" error_message = 'File not found.'
  • list (List): An ordered collection of values. Enclosed in [] and separated by commas.Pythonscores = [88, 92, 75, 100] items = ["Apple", 150, True]
  • tuple (Tuple): An ordered collection of values. Enclosed in (). It is similar to a list, but its contents cannot be changed (immutable) once created.Pythondb_config = ("localhost", 5432, "admin")
  • dict (Dictionary): A collection storing Key-Value pairs. Enclosed in {} in the format key: value.Pythonuser_profile = {"id": "A001", "age": 45, "name": "Sato"}
  • set (Set): An unordered collection containing unique values (no duplicates). Enclosed in {}.Pythonunique_tags = {"python", "dev", "web", "python"} # The content of unique_tags becomes {"python", "dev", "web"}

Important Properties of Variables

Understanding the following two properties is very important when working with data types.

1. Mutable vs. Immutable

This classification indicates whether data (an object) can be changed after it is created.

Immutable (Unchangeable) Once created, the content of the object itself cannot be changed. Main types: int, float, bool, str, tuple

# String (str) example
app_name = "MyApp"
# It looks like we are changing the content of app_name...
app_name = "NewApp" 
# ...but actually, a NEW string object "NewApp" is created,
# and app_name is just updated to point to it.

# Tuple (tuple) example
coordinates = (10, 20)
# coordinates[0] = 5  # TypeError: 'tuple' object does not support item assignment

Mutable (Changeable) The content of the object itself can be changed after creation. Main types: list, dict, set

# List (list) example
active_users = ["Tanaka", "Suzuki"]
print(f"Before: {active_users}")

# Modify the object active_users itself
active_users.append("Kato") 

print(f"After: {active_users}")

# Dictionary (dict) example
settings = {"theme": "dark"}
print(f"Before: {settings}")

# Add a key and value to the settings object itself
settings["font_size"] = 16

print(f"After: {settings}")

Output:

Before: ['Tanaka', 'Suzuki']
After: ['Tanaka', 'Suzuki', 'Kato']
Before: {'theme': 'dark'}
After: {'theme': 'dark', 'font_size': 16}

2. Iterable

“Iterable” means an object whose elements can be retrieved one by one, such as in a for loop. Python collection types (list, tuple, str, dict, set) are all iterable.

# List (Iterable) example
user_roles = ["admin", "editor", "guest"]
print("--- User Roles ---")
for role in user_roles:
    print(role)

# String (Iterable) example
app_version = "1.5.0"
print("--- Version Details ---")
for char in app_version:
    print(char)

# Dictionary (Iterable) example
# By default, it iterates over Keys
user_scores = {"tanaka": 80, "suzuki": 95}
print("--- User Scores (Keys) ---")
for user in user_scores:
    print(user)

# Use .items() to get both Key and Value
print("--- User Scores (Key and Value) ---")
for user, score in user_scores.items():
    print(f"{user}: {score}")

Output:

--- User Roles ---
admin
editor
guest
--- Version Details ---
1
.
5
.
0
--- User Scores (Keys) ---
tanaka
suzuki
--- User Scores (Key and Value) ---
tanaka: 80
suzuki: 95

Summary

Python variables can handle various types of data, from basic types like int and str to powerful collection types like list and dict.

  • list and dict are Mutable (changeable).
  • str and tuple are Immutable (unchangeable).
  • Objects where you can extract elements one by one in a for loop (like list, str, dict) are Iterable.

Understanding these data types and their properties will help you use Python more effectively.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次