Pythonを学び始めたばかりの人にとって、「データ型」はとても大事な概念です。
「数字」「文字」「リスト」「真偽値」など、プログラムで扱う値にはそれぞれ型(Type)があり、型によって使える操作や挙動が変わります。
この記事では、Pythonの代表的なデータ型を、わかりやすい例と一緒に初心者向けに紹介します。
プログラミング未経験の方でも安心して読めるよう、丁寧に解説していきます!
データ型とは?なぜ重要なのか

データ型の基本概念
データ型とは、コンピューターがデータをどのように扱うかを決める仕組みです。
例えば、数字の「3」と文字の「3」は見た目は同じでも、コンピューターにとっては全く違うものです。
# 数字の3
number = 3
print(number + 2) # 5(計算できる)
# 文字の「3」
text = "3"
print(text + "2") # "32"(文字として結合される)
なぜデータ型が重要なのか?
- エラーの防止 正しい型を使うことで、予期しないエラーを防げます
- 効率的な処理 適切な型を選ぶことで、メモリ使用量や処理速度が改善されます
- コードの可読性 型が明確だと、コードが読みやすくなります
- デバッグの簡素化 問題の原因を特定しやすくなります
Pythonの基本データ型一覧
主要なデータ型の分類
カテゴリ | データ型 | 説明 | 例 |
---|---|---|---|
数値型 | int | 整数 | 1 , -10 , 2024 |
float | 小数 | 3.14 , -0.5 , 2.0 | |
complex | 複素数 | 1+2j , 3-4j | |
文字型 | str | 文字列 | "Hello" , 'Python' |
真偽型 | bool | 真偽値 | True , False |
シーケンス型 | list | リスト(変更可) | [1, 2, 3] , ['a', 'b'] |
tuple | タプル(変更不可) | (1, 2, 3) , ('x', 'y') | |
range | 連続数値 | range(10) | |
マッピング型 | dict | 辞書 | {"name": "Alice", "age": 30} |
集合型 | set | 集合(重複なし) | {1, 2, 3} |
frozenset | 変更不可集合 | frozenset({1, 2, 3}) | |
特殊型 | NoneType | 値なし | None |
型の確認方法
# type()関数で型を確認
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
# isinstance()関数で型をチェック
print(isinstance(42, int)) # True
print(isinstance(3.14, float)) # True
print(isinstance("hello", str)) # True
ポイント: Pythonでは、扱うデータの種類ごとに型が異なり、使い方も変わることを覚えましょう。
数値型(int・float・complex)|計算の基本になる型

int型(整数)
# 基本的な整数
x = 10
y = -3
z = 0
print(x + y) # 7
print(x * y) # -30
print(x // y) # -4(整数除算)
print(x ** 2) # 100(べき乗)
# 大きな数値も扱える
big_number = 123456789012345678901234567890
print(big_number) # Pythonは任意精度の整数をサポート
float型(浮動小数点数)
# 小数の基本操作
pi = 3.14159
radius = 2.5
# 円の面積を計算
area = pi * radius ** 2
print(f"円の面積: {area}") # 円の面積: 19.634875
# 浮動小数点の注意点
print(0.1 + 0.2) # 0.30000000000000004(丸め誤差)
# 正確な計算が必要な場合はDecimalを使用
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2')) # 0.3
complex型(複素数)
# 複素数の表現
z1 = 3 + 4j
z2 = 1 - 2j
print(z1 + z2) # (4+2j)
print(z1 * z2) # (11-2j)
print(abs(z1)) # 5.0(絶対値)
# 実部と虚部の取得
print(z1.real) # 3.0
print(z1.imag) # 4.0
数値型の変換
# 型変換の例
x = 10
print(float(x)) # 10.0
print(complex(x)) # (10+0j)
y = 3.14
print(int(y)) # 3(小数部切り捨て)
# 文字列から数値への変換
num_str = "123"
print(int(num_str)) # 123
print(float(num_str)) # 123.0
文字列型(str)|文章やデータ入力に欠かせない

文字列の基本操作
# 文字列の作成
name = "Alice"
message = 'Hello, World!'
multiline = """これは
複数行の
文字列です"""
# 文字列の連結
greeting = "Hello, " + name
print(greeting) # Hello, Alice
# f-string(推奨)
age = 25
print(f"{name}は{age}歳です") # Aliceは25歳です
文字列の操作とメソッド
text = "Python Programming"
# インデックスとスライス
print(text[0]) # P(最初の文字)
print(text[-1]) # g(最後の文字)
print(text[0:6]) # Python(0番目から5番目まで)
print(text[:6]) # Python(最初から5番目まで)
print(text[7:]) # Programming(7番目から最後まで)
# 便利なメソッド
print(text.lower()) # python programming
print(text.upper()) # PYTHON PROGRAMMING
print(text.replace("Python", "Java")) # Java Programming
print(text.split()) # ['Python', 'Programming']
print(len(text)) # 18(文字数)
# 文字列の判定
print(text.startswith("Python")) # True
print(text.endswith("ing")) # True
print("gram" in text) # True
文字列のフォーマット
name = "Bob"
score = 85.5
# 様々なフォーマット方法
print("名前: %s, 点数: %.1f" % (name, score)) # 古い方法
print("名前: {}, 点数: {:.1f}".format(name, score)) # .format()
print(f"名前: {name}, 点数: {score:.1f}") # f-string(推奨)
# f-stringの高度な使い方
import datetime
now = datetime.datetime.now()
print(f"現在時刻: {now:%Y-%m-%d %H:%M:%S}")
リスト(list)とタプル(tuple)|複数データをまとめて扱う

list型(変更可能なシーケンス)
# リストの作成
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True] # 異なる型を混在可能
# 要素へのアクセス
print(fruits[0]) # apple
print(fruits[-1]) # cherry(最後の要素)
# リストの変更
fruits.append("grape") # 末尾に追加
fruits.insert(1, "orange") # 指定位置に挿入
fruits.remove("banana") # 値で削除
deleted = fruits.pop() # 末尾を削除して取得
print(fruits) # ['apple', 'orange', 'cherry']
# リストの操作
print(len(fruits)) # 3(要素数)
print("apple" in fruits) # True(存在確認)
fruits.sort() # ソート
fruits.reverse() # 逆順
tuple型(変更不可能なシーケンス)
# タプルの作成
colors = ("red", "green", "blue")
point = (10, 20)
single = (42,) # 要素が1つの場合はカンマが必要
# タプルは変更できない
# colors[0] = "yellow" # TypeError!
# タプルの利点
coordinates = (3.5, 7.2)
x, y = coordinates # アンパック(分解代入)
print(f"x: {x}, y: {y}") # x: 3.5, y: 7.2
# 関数で複数の値を返す
def get_name_age():
return "Alice", 30
name, age = get_name_age()
print(f"{name}は{age}歳です")
リストとタプルの使い分け
特徴 | list | tuple |
---|---|---|
変更可能性 | 変更可能 | 変更不可 |
パフォーマンス | やや遅い | 高速 |
メモリ使用量 | 多い | 少ない |
使用場面 | データの追加・削除が必要 | 固定データ、座標、設定値 |
辞書型(dict)|「キー」と「値」のペア
辞書の基本操作
# 辞書の作成
person = {"name": "Bob", "age": 30, "city": "Tokyo"}
empty_dict = {}
# 値の取得
print(person["name"]) # Bob
print(person.get("age")) # 30
print(person.get("height", "不明")) # 不明(デフォルト値)
# 値の追加・更新
person["age"] = 31 # 既存キーを更新
person["email"] = "bob@example.com" # 新しいキーを追加
person.update({"phone": "090-1234-5678", "job": "engineer"})
print(person)
# {'name': 'Bob', 'age': 31, 'city': 'Tokyo', 'email': 'bob@example.com', 'phone': '090-1234-5678', 'job': 'engineer'}
辞書の操作メソッド
student = {"name": "Alice", "math": 85, "english": 92, "science": 78}
# キー、値、アイテムの取得
print(student.keys()) # dict_keys(['name', 'math', 'english', 'science'])
print(student.values()) # dict_values(['Alice', 85, 92, 78])
print(student.items()) # dict_items([('name', 'Alice'), ('math', 85), ...])
# ループ処理
for key in student:
print(f"{key}: {student[key]}")
for key, value in student.items():
print(f"{key}: {value}")
# 要素の削除
del student["name"] # キーで削除
score = student.pop("math") # 削除して値を取得
print(score) # 85
辞書の実用例
# 商品在庫管理
inventory = {
"apple": 50,
"banana": 30,
"orange": 25
}
# 在庫確認
product = "apple"
if product in inventory:
print(f"{product}の在庫: {inventory[product]}個")
# 売上集計
sales = {}
purchases = ["apple", "banana", "apple", "orange", "apple"]
for item in purchases:
if item in sales:
sales[item] += 1
else:
sales[item] = 1
print(sales) # {'apple': 3, 'banana': 1, 'orange': 1}
集合型(set)|重複を排除するデータ型

集合の基本操作
# 集合の作成
numbers = {1, 2, 3, 3, 4, 4, 5}
print(numbers) # {1, 2, 3, 4, 5}(重複が自動で除去)
# リストから集合を作成(重複削除)
fruits_list = ["apple", "banana", "apple", "cherry", "banana"]
fruits_set = set(fruits_list)
print(fruits_set) # {'cherry', 'banana', 'apple'}
# 要素の追加・削除
fruits_set.add("grape") # 要素追加
fruits_set.remove("banana") # 要素削除(存在しない場合はエラー)
fruits_set.discard("orange") # 要素削除(存在しなくてもエラーなし)
集合演算
# 2つの集合
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# 和集合(union)
print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b)) # 同じ結果
# 積集合(intersection)
print(a & b) # {4, 5}
print(a.intersection(b)) # 同じ結果
# 差集合(difference)
print(a - b) # {1, 2, 3}
print(a.difference(b)) # 同じ結果
# 対称差集合(symmetric difference)
print(a ^ b) # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b)) # 同じ結果
集合の実用例
# 重複する値の検出
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
data = [1, 2, 3, 2, 4, 3, 5, 1]
print(find_duplicates(data)) # [1, 2, 3]
# 共通の趣味を持つ人を見つける
alice_hobbies = {"reading", "swimming", "coding"}
bob_hobbies = {"swimming", "gaming", "cooking"}
charlie_hobbies = {"reading", "gaming", "swimming"}
common_hobbies = alice_hobbies & bob_hobbies & charlie_hobbies
print(f"3人の共通趣味: {common_hobbies}") # {'swimming'}
真偽値(bool)とNone|条件判定と空の値
bool型の基本
# 真偽値の作成
is_sunny = True
is_raining = False
# 比較演算の結果
x = 5
print(x > 3) # True
print(x < 2) # False
print(x == 5) # True
print(x != 5) # False
# 論理演算
print(True and False) # False
print(True or False) # True
print(not True) # False
Truthyと Falsyな値
# Falsyな値(Falseとして扱われる)
print(bool(False)) # False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False(空文字列)
print(bool([])) # False(空リスト)
print(bool({})) # False(空辞書)
print(bool(set())) # False(空集合)
print(bool(None)) # False
# Truthyな値(Trueとして扱われる)
print(bool(True)) # True
print(bool(1)) # True
print(bool(-1)) # True
print(bool("hello")) # True
print(bool([1, 2])) # True
print(bool({"a": 1})) # True
None型
# Noneの使用例
result = None
def search_user(user_id):
if user_id == 1:
return {"name": "Alice", "age": 30}
else:
return None # ユーザーが見つからない場合
user = search_user(2)
if user is None:
print("ユーザーが見つかりませんでした")
else:
print(f"ユーザー名: {user['name']}")
# Noneのチェック方法
value = None
print(value is None) # True(推奨)
print(value == None) # True(非推奨)
print(value is not None) # False
データ型の変換(キャスト)

基本的な型変換
# 文字列から数値への変換
num_str = "123"
print(int(num_str)) # 123
print(float(num_str)) # 123.0
price_str = "19.99"
print(float(price_str)) # 19.99
# 数値から文字列への変換
age = 25
print(str(age)) # "25"
print(f"年齢: {age}") # f-stringも内部で変換
# リストとタプルの相互変換
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # (1, 2, 3)
back_to_list = list(my_tuple) # [1, 2, 3]
# 文字列をリストに変換
text = "hello"
char_list = list(text) # ['h', 'e', 'l', 'l', 'o']
変換時の注意点とエラーハンドリング
# 変換できない場合のエラー
try:
num = int("abc")
except ValueError as e:
print(f"変換エラー: {e}")
# 安全な変換関数
def safe_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
print(safe_int("123")) # 123
print(safe_int("abc")) # 0
print(safe_int(None)) # 0
# 小数を整数に変換するときの注意
print(int(3.9)) # 3(切り捨て)
print(round(3.9)) # 4(四捨五入)
import math
print(math.floor(3.9)) # 3(床関数)
print(math.ceil(3.1)) # 4(天井関数)
型変換の一覧表
変換先 | 関数 | 例 | 結果 |
---|---|---|---|
整数 | int() | int("123") | 123 |
浮動小数点 | float() | float("3.14") | 3.14 |
文字列 | str() | str(123) | "123" |
リスト | list() | list("abc") | ['a', 'b', 'c'] |
タプル | tuple() | tuple([1, 2, 3]) | (1, 2, 3) |
集合 | set() | set([1, 2, 2, 3]) | {1, 2, 3} |
辞書 | dict() | dict([('a', 1), ('b', 2)]) | {'a': 1, 'b': 2} |
真偽値 | bool() | bool("hello") | True |
実践的な使用例
データ分析での型活用
# 学生の成績データ
students = [
{"name": "Alice", "scores": [85, 92, 78]},
{"name": "Bob", "scores": [90, 85, 88]},
{"name": "Charlie", "scores": [78, 85, 92]}
]
# 各学生の平均点を計算
for student in students:
name = student["name"]
scores = student["scores"]
average = sum(scores) / len(scores)
print(f"{name}の平均点: {average:.1f}")
# 全体の最高点を見つける
all_scores = []
for student in students:
all_scores.extend(student["scores"])
max_score = max(all_scores)
print(f"全体の最高点: {max_score}")
ファイル処理での型活用
# CSVデータの処理例
csv_data = """name,age,city
Alice,25,Tokyo
Bob,30,Osaka
Charlie,28,Kyoto"""
lines = csv_data.strip().split('\n')
header = lines[0].split(',')
data = []
for line in lines[1:]:
values = line.split(',')
record = {}
for i, value in enumerate(values):
key = header[i]
# 数値に変換できる場合は変換
if key == 'age':
record[key] = int(value)
else:
record[key] = value
data.append(record)
print(data)
# [{'name': 'Alice', 'age': 25, 'city': 'Tokyo'}, ...]
よくある質問と答え
Q: PythonではC言語のような型宣言は必要ですか?
A: 不要です。Pythonは動的型付け言語なので、変数に値を代入すると自動的に型が決まります。
Q: 型を間違えるとどうなりますか?
A: 実行時にTypeErrorが発生します。例:"hello" + 123
Q: 型ヒント(Type Hints)とは何ですか?
A: Python 3.5以降で導入された、コードに型情報を付加する機能です。実行には影響しませんが、コードの可読性が向上します。
Q: listとtupleはどう使い分けますか?
A: データを変更する可能性があるならlist、変更しない固定データならtupleを使用します。
まとめ:Pythonのデータ型をマスターして、効率的なプログラミングを!
重要ポイントまとめ:
- 各データ型には特徴と適切な使用場面がある
- 型を意識することでバグの少ないコードが書ける
- 型変換を理解することで柔軟なデータ処理が可能
- 実際のプロジェクトでは複数の型を組み合わせて使用
Pythonでは、型を意識してコードを書くことがとても重要です。
それぞれのデータ型には特徴と用途があり、正しく使い分けることで、より効率的でバグの少ないコードが書けるようになります。
最低限覚えておきたい基本型:
- 数字 →
int
,float
- 文字列 →
str
- シーケンス →
list
,tuple
- マッピング →
dict
- 集合 →
set
- 判定 →
bool
,None
コメント