0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Python データタイプ完全ガイド

Posted at

はじめに

「変数は箱ではなく“ラベル”。データはオブジェクト。」
この一言を理解すれば、Python のデータ型は一気にクリアになる。

Python は「変数=参照(reference)」という仕組みの言語。
データの“本体”はオブジェクト、変数はただの名前。
この仕組みを理解すると、可変/不可変の挙動や、あの “default 引数の罠” もスッと腑に落ちる。

この記事では、Python の主要データ型を網羅しつつ、実務で重要なポイントを前提知識ゼロで分かりやすく解説する。


1. Python の主要データ型一覧

■ 基本データ型(Primitive)

特徴
int 42 大きさ無制限の整数
float 3.14 浮動小数点
bool True / False int のサブクラス(重要)
str "hello" 文字列(immutable)

■ コンテナ型(Container)

特徴
list [1,2,3] 可変(mutable)
tuple (1,2,3) 不可変(immutable)
dict {"a":1} 可変、キーと値
set {1,2,3} 可変、重複なし

2. 可変(mutable) vs 不可変(immutable)

Python の挙動を理解する上で最重要ポイント。

■ 不可変(immutable)

  • int
  • float
  • bool
  • str
  • tuple

不可変とは 中身を書き換えられない という意味。

s = "hello"
s += " world"

これは「hello」の後ろに文字を追加したのではなく、

  • 新しい "hello world" オブジェクトを作って
  • s の参照先をそちらに変更した

という動作になる。

■ 可変(mutable)

  • list
  • dict
  • set

例:

arr = [1,2,3]
arr.append(4)   # arr の中身がそのまま変わる

3. Python の「default 引数の罠」

Python 初心者が必ず踏む大地雷。
あなたも見たことがあるかもしれない、このコード:

def f(x=[]):
    x.append(1)
    return x

なぜ同じリストが使い続けられるのか?

理由はシンプル:

  • 【重要】デフォルト値は「関数定義時に1回だけ」作られる

つまり [] は毎回新しく作られない。

関数定義時に:

  • 一個の空リストが作成
  • これがずっと f のデフォルト値として保持される

その結果:

f()  # [1]
f()  # [1, 1]
f()  # [1, 1, 1]

と恐ろしいことになる。

正しい書き方

def f(x=None):
    if x is None:
        x = []
    x.append(1)
    return x

4. type() と isinstance()

Pythonでは型をチェックする方法が2つある。

type(obj)

ピンポイントで“その型だけ”。
継承は無視。

isinstance(obj, クラス) ← こちら推奨

継承も含めて判定。

例:

isinstance(True, int)  # True。

なぜ?
→ Python では bool は int のサブクラス だから。


5. NoneType

Python の特殊型。
唯一の値は None

  • 「値がない」
  • 「まだ決まってない」
  • 「空の戻り値」

などに使われる。


6. Python の型は“実行時に決まる”:Dynamic Typing

Python は 動的型付け の代表選手。

  • 変数に型はない

  • オブジェクトに型がある

  • 変数はただの名前

これが根底にある。


まとめ

  • データはオブジェクト、そのオブジェクトが型を持つ
  • 基本型はすべて immutable
  • list/dict/set は mutable
  • default 引数に mutable を使うと事故る
  • isinstance を推奨
  • None は NoneType の唯一の値
  • Python は動的型付けで、変数が型を持たない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?