Python基本関数・メソッド完全一覧【初心者向け保存版】

 

Pythonプログラミングを学習する上で、基本的な関数とメソッドの理解は必須です。この記事では、Python初心者から中級者まで役立つ基本関数とメソッドを体系的にまとめました。実際のコード例とともに、実務でよく使われる重要な関数・メソッドを厳選してご紹介します。

目次

  1. Python基本関数とは
  2. 組み込み関数一覧
  3. 文字列メソッド一覧
  4. リストメソッド一覧
  5. 辞書メソッド一覧
  6. 数値・数学関数
  7. ファイル操作関数
  8. まとめ

Python基本関数とは

Python基本関数は、Pythonに標準で組み込まれている関数のことです。特別にインポートする必要がなく、どこでも使用できる便利な機能です。これらの関数を理解することで、効率的なPythonプログラミングが可能になります。

組み込み関数一覧

基本的な入出力関数

print() – 値を出力

print("Hello, World!")
print(1, 2, 3, sep=", ")  # 区切り文字を指定

input() – ユーザーからの入力を受け取る

name = input("名前を入力してください: ")
age = int(input("年齢を入力してください: "))

データ型変換関数

int() – 整数に変換

num = int("123")  # 文字列を整数に
num = int(3.14)   # 浮動小数点数を整数に

float() – 浮動小数点数に変換

price = float("99.99")

str() – 文字列に変換

text = str(123)
text = str(3.14)

bool() – 真偽値に変換

result = bool(1)     # True
result = bool(0)     # False
result = bool("")    # False

コレクション操作関数

len() – 長さを取得

length = len("Hello")      # 5
length = len([1, 2, 3])    # 3
length = len({"a": 1})     # 1

max() – 最大値を取得

maximum = max([1, 5, 3])   # 5
maximum = max("hello")     # 'o'

min() – 最小値を取得

minimum = min([1, 5, 3])   # 1
minimum = min("hello")     # 'e'

sum() – 合計値を計算

total = sum([1, 2, 3, 4])  # 10

sorted() – ソートされた新しいリストを返す

sorted_list = sorted([3, 1, 4, 1, 5])  # [1, 1, 3, 4, 5]
sorted_list = sorted(["banana", "apple", "cherry"])

reversed() – 逆順のイテレータを返す

reversed_list = list(reversed([1, 2, 3]))  # [3, 2, 1]

条件・判定関数

any() – いずれかがTrueならTrue

result = any([False, True, False])   # True
result = any([0, 1, 2])              # True

all() – すべてがTrueならTrue

result = all([True, True, True])     # True
result = all([1, 2, 3])              # True
result = all([1, 0, 3])              # False

反復処理関数

range() – 数値の範囲を生成

for i in range(5):           # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):        # 1, 2, 3, 4, 5
    print(i)

for i in range(0, 10, 2):    # 0, 2, 4, 6, 8
    print(i)

enumerate() – インデックス付きで反復

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

zip() – 複数のイテラブルを組み合わせ

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name}: {age}歳")

文字列メソッド一覧

文字列オブジェクトで使用できる主要なメソッドをご紹介します。

文字列の変換・整形

upper() – 大文字に変換

text = "hello world"
print(text.upper())  # HELLO WORLD

lower() – 小文字に変換

text = "HELLO WORLD"
print(text.lower())  # hello world

capitalize() – 最初の文字を大文字に

text = "hello world"
print(text.capitalize())  # Hello world

title() – 各単語の最初を大文字に

text = "hello world"
print(text.title())  # Hello World

strip() – 前後の空白を削除

text = "  hello world  "
print(text.strip())  # hello world

replace() – 文字列を置換

text = "Hello World"
print(text.replace("World", "Python"))  # Hello Python

文字列の検索・判定

find() – 文字列を検索(インデックスを返す)

text = "Hello World"
index = text.find("World")  # 6
index = text.find("Python") # -1(見つからない場合)

startswith() – 指定文字列で始まるかチェック

text = "Hello World"
result = text.startswith("Hello")  # True

endswith() – 指定文字列で終わるかチェック

text = "Hello World"
result = text.endswith("World")    # True

isdigit() – 数字のみかチェック

text1 = "123"
text2 = "12a"
print(text1.isdigit())  # True
print(text2.isdigit())  # False

isalpha() – アルファベットのみかチェック

text1 = "Hello"
text2 = "Hello123"
print(text1.isalpha())  # True
print(text2.isalpha())  # False

文字列の分割・結合

split() – 文字列を分割してリストに

text = "apple,banana,cherry"
fruits = text.split(",")  # ['apple', 'banana', 'cherry']

join() – リストを文字列に結合

fruits = ['apple', 'banana', 'cherry']
text = ", ".join(fruits)  # apple, banana, cherry

リストメソッド一覧

リストオブジェクトで使用できる主要なメソッドをご紹介します。

要素の追加・削除

append() – 末尾に要素を追加

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # ['apple', 'banana', 'cherry']

insert() – 指定位置に要素を挿入

fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits)  # ['apple', 'banana', 'cherry']

remove() – 指定要素を削除

fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # ['apple', 'cherry']

pop() – 指定位置の要素を削除して返す

fruits = ["apple", "banana", "cherry"]
removed = fruits.pop(1)  # banana
print(fruits)            # ['apple', 'cherry']

clear() – すべての要素を削除

fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)  # []

リストの操作

sort() – リストをソート(元のリストを変更)

numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # [1, 1, 3, 4, 5]

# 降順でソート
numbers.sort(reverse=True)
print(numbers)  # [5, 4, 3, 1, 1]

reverse() – リストを逆順に(元のリストを変更)

numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)  # [5, 4, 3, 2, 1]

copy() – リストのコピーを作成

original = [1, 2, 3]
copied = original.copy()

要素の検索・カウント

index() – 指定要素のインデックスを取得

fruits = ["apple", "banana", "cherry"]
index = fruits.index("banana")  # 1

count() – 指定要素の出現回数をカウント

numbers = [1, 2, 3, 2, 2, 4]
count = numbers.count(2)  # 3

辞書メソッド一覧

辞書オブジェクトで使用できる主要なメソッドをご紹介します。

キー・値の取得

keys() – すべてのキーを取得

person = {"name": "Alice", "age": 25, "city": "Tokyo"}
keys = list(person.keys())  # ['name', 'age', 'city']

values() – すべての値を取得

person = {"name": "Alice", "age": 25, "city": "Tokyo"}
values = list(person.values())  # ['Alice', 25, 'Tokyo']

items() – キーと値のペアを取得

person = {"name": "Alice", "age": 25, "city": "Tokyo"}
for key, value in person.items():
    print(f"{key}: {value}")

get() – キーに対応する値を安全に取得

person = {"name": "Alice", "age": 25}
name = person.get("name", "Unknown")      # Alice
country = person.get("country", "Japan")  # Japan(デフォルト値)

辞書の更新・操作

update() – 辞書を更新

person = {"name": "Alice", "age": 25}
person.update({"city": "Tokyo", "age": 26})
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'Tokyo'}

pop() – 指定キーの要素を削除して値を返す

person = {"name": "Alice", "age": 25, "city": "Tokyo"}
age = person.pop("age")  # 25
print(person)            # {'name': 'Alice', 'city': 'Tokyo'}

clear() – すべての要素を削除

person = {"name": "Alice", "age": 25}
person.clear()
print(person)  # {}

copy() – 辞書のコピーを作成

original = {"name": "Alice", "age": 25}
copied = original.copy()

数値・数学関数

基本的な数学関数

abs() – 絶対値を取得

result = abs(-5)    # 5
result = abs(3.14)  # 3.14

round() – 四捨五入

result = round(3.14159)     # 3
result = round(3.14159, 2)  # 3.14

pow() – べき乗を計算

result = pow(2, 3)    # 8
result = pow(2, 3, 5) # 8 % 5 = 3(剰余付き)

divmod() – 商と余りを同時に取得

quotient, remainder = divmod(17, 5)  # (3, 2)

ファイル操作関数

open() – ファイルを開く

# ファイルを読み込みモードで開く
with open("sample.txt", "r", encoding="utf-8") as file:
    content = file.read()

# ファイルを書き込みモードで開く
with open("output.txt", "w", encoding="utf-8") as file:
    file.write("Hello, World!")

まとめ

Pythonの基本関数とメソッドは、効率的なプログラミングの基盤となる重要な要素です。この記事で紹介した関数・メソッドを理解し、実際のコードで活用することで、より洗練されたPythonプログラムを作成できるようになります。

特に重要なポイントは以下の通りです:

  • 組み込み関数は特別なインポートなしで使用可能
  • 文字列メソッドはテキスト処理に必須
  • リストメソッドはデータの操作・管理に不可欠
  • 辞書メソッドはキー・値ペアの効率的な処理に必要

これらの基本関数・メソッドをマスターすることで、Pythonプログラミングのスキルが大幅に向上します。実際のプロジェクトで積極的に活用し、より高度なPythonプログラミングへとステップアップしていきましょう。

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>理系出身者向けのPython爆速講座