LoginSignup
3
6

More than 1 year has passed since last update.

【Python】Pythonの主な組み込み関数31個について、全て例を交えて解説する

Last updated at Posted at 2022-11-23

始めに

こちらの参考書でPythonを勉強しています。
Chapter6第2部に組み込み関数が大量に紹介されていたので、触ってみるついでに紹介していきます!

紹介!

ではどうぞ!
マイルールで見出しレベル調整してたら見づらくなったかもしれません。右のナビゲーションを参考にしてください...
難しめな用語の脚注も載せておりますのでご覧ください。

1. 計算

1-1. 絶対値を返す

abs(x)
example.py
abs(-10) # 10
abs(-0) # 0

複素数の絶対値を求めるためにも使える。

abs(complex(1, 2)) # 2.23606797749979
# complex(x, y) = x+yj

1-2. 最大値を返す

1-2-1. イテラブル1の最大値を返す

max(iterable)
example.py
# リスト
max([90, 92, 75, 92, 85, 60]) # 92
# タプル
max((108, 112, 118, 68, 72, 47)) # 118
# 集合
max({67, 89, 116, 79, 116, 33}) # 116
# 辞書
Dragonite = {'H':91, 'A':134, 'B':95, 'C':100, 'D':100, 'S':80}
max(Dragonite) # S
max(Dragonite.values()) # 134
# 文字列
max('Hello') # o
# 混合
max(('', '', '', '', 2)) # エラー

アルファベットは降順のためzが最も大きく、小文字のほうが大文字より大きいとみなされる。
(A<B<...<Y<Z<a<b<...<y<z)

1-2-2. 複数の引数の内の最大値を返す

max(arg1, arg2, arg3)
example.py
max(108, 130, 85, 80, 95, 102) # 130
max('', '', '', '', '') # 乙

1-3. 最小値を返す

1-3-1. イテラブルの最小値を返す

min(iterable)
example.py
# リスト
min([90, 92, 75, 92, 85, 60]) # 60
# タプル
min(108, 112, 118, 68, 72, 47)) # 47
# 集合
min({67, 89, 116, 79, 116, 33}) # 33
# 辞書
Dragonite = {'H':91, 'A':134, 'B':95, 'C':100, 'D':100, 'S':80}
min(Dragonite) # A
min(Dragonite.values()) # 80
# 文字列
min('Hello') # H
# 混合
min(('', '', '', '', 2)) # エラー

1-3-2. 複数の引数の内の最小値を返す

min(arg1, arg2, arg3)
example.py
min(108, 130, 85, 80, 95, 102) # 80
min('', '', '', '', '') # ゴ

1-4. イテラブルの要素の合計を返す

sum(iterable[, add])
example.py
sum(90, 92, 75, 92, 85, 60) # エラー
sum([67, 89, 116, 79, 116, 33]) # 500
sum({67, 89, 116, 79, 116, 33}) # 384
sum([67, 89, 116, 79, 116, 33], 10000.2) # 10500.2
sum([67, 89, 116], [79, 116, 33]) # エラー
sum([True, False, 100, True*10]) # 111
# True=1, False=0として計算される。

sum関数は基本はリストに用いられる
第2引数addは省略可能で計算結果に加える数。数値しか入らない。

ちなみに、

sum([67, 89, 116, 79, 116, 33]) # 500
sum({67, 89, 116, 79, 116, 33}) # 384

の値が異なるのは、リスト型は重複した要素を無視しないのに対し、集合型は重複を無視することが原因。

2. 文字

2-1. 整数iのUnicodeコードポイントを持つ文字を表す文字列を表す

chr(i)
example.py
chr(102) # f
chr(50) # 2
chr('5') # エラー

2-2. 1文字のUnicode文字を表す文字列cのUnicodeコードポイントを表す整数を返す

ord(c)
example.py
ord('f') # 102
ord('2') # 50
ord(5) # エラー
ord('主人公') # エラー

3. 入出力

3-1. ユーザからの入力を受け付けて文字列として返す

input([prompt])
example.py
a = input()
print(a) # (入力された文字列)
b = input('好きな文字を入力してください')
print(b) # (入力された文字列)

promptを設定した場合、下のように表示される。
image.png

3-2. オブジェクト*objectsを、区切り文字sepで区切りながら出力し、最後にendで指定した文字列を出力する

print(*objects, sep='', end='./')
example.py
gabu = [108, 130, 85, 80, 95, 102]
print(*gabu, sep=' ', end=' 終わり')
# 108 130 85 80 95 102 終わり

4. オブジェクト

4-1. オブジェクトobjectの識別値を返す

id(object)
example.py
import copy
gabu = [108, 130, 85, 80, 95, 102]
metamon = gabu
gabu_copy = gabu.copy() # シャローコピー
gabu_deepcopy = copy.deepcopy(gabu) # ディープコピー

# 参照しているオブジェクトが同じかどうか確かめるときに使える
print(id(gabu)) # 3067230143040
print(id(metamon)) # 3067230143040
print(id(gabu_copy)) # 3067230133056
print(id(gabu_deepcopy)) # 3067230207808

print(id(gabu)==id(metamon)) # True
print(id(gabu)==id(gabu_copy)) # False
print(id(gabu)==id(gabu_deepcopy)) # False

4-2. オブジェクトobjectの型を返す

type(object)
example.py
type(gabu) # <class 'list'>
type(3) # <class 'int'>
type('gabu') # <class 'str'>
type({'name': gabu}) # <class 'dict'>
type(None) # <class 'NoneType'>
type(Undefined) # <class 'type'>

4-3. オブジェクトobjectの属性のリストを返す

dir([object])
example.py
dir(copy)
# ['Error', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_copy_dispatch', '_copy_immutable', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', 'copy', 'deepcopy', 'dispatch_table', 'error']

特定のパッケージやモジュールの持つ属性を知りたい場合に利用する。
これを用いて取得した属性のうち、気になる名前の属性があればhelp()メソッドを用いてその関数の使い方を調べることが出来る。

help(copy._deepcopy_tuple)
# Help on function _deepcopy_tuple in module copy:    
# 
# _deepcopy_tuple(x, memo, deepcopy=<function deepcopy at 0x0000019669 at 0x00000196695F1550>)
# 
# None

4-4. オブジェクトsの長さ(要素の数を返す)

len(s)
example.py
gabu = [108, 130, 85, 80, 95, 102]
len(gabu) # 6
kyogre = {
    'H': 100,
    'A': 100,
    'B': 90,
    'C': 150,
    'D': 140,
    'S': 90
}
len(kyogre) # 6
len('Garchomp is a hero.') # 19
len(3) # エラー

5. データ型

5-1. 数値または文字列xから整数を生成して返す

int([x])
example.py
int(7) # エラー
int('7') # 7
int() # 0
int(3.999) # 3

第2引数に何進数で処理するか指定することもできる。

example.py
int('A') # エラー
int('A', 16) # 10
int('10', 2) # 2

5-2. 数値または文字列xから浮動小数点数を生成して返す

float([x])
example.py
float(3.14) # 3.14
float('3.14') # 3.14
float() # 0.0
float('2.52e+2') # 252.0
float('101.01', 2) # エラー

float()int()と違って引数は1つまでしか持てない。

5-3. オブジェクトxからブール値を生成して返す

bool([x])
example.py
bool() # False
bool(0) # False
bool(1) # True
bool('') # False
bool('Zapdos') # True
bool(True) # True
bool(False) # False
bool(None) # False

5-4. 開始、終了およびステップを表す整数start, stop, stepからrangeを生成する

5-4-1. 引数がひとつの場合

range(stop)
example.py
for i in range(3):
    print(i)
# 0 1 2
list(range(3)) # 0 1 2

0以上stop未満

5-4-2. 引数が複数(2, 3)の場合

range(start, stop[, step])
example.py
for i in range(3, 8):
    print(i)
# 3 4 5 6 7
for i in range(3, 8, 2):
    print(i)
# 3 5 7
for i in range(-10, 0, 2):
    print(i)
# -10 -8 -6 -4 -2
for i in range(0, 5, 1.5):
    print(i)
# エラー
for i in range(0, 3, True):
    print(i)
# 0 1 2
lst = list(range(1, 10, 2))
# [1, 3, 5, 7, 9]

list()は少し下に解説あります。

5-5. オブジェクトobjectから文字列を生成して返す

str(object='')
example.py
print('Kyogre\'s C is ' + 150) # エラー
print('Kyogre\'s C is ' + str(150)) # Kyogre's C is 150
print('Kyogre: ' + [100, 100, 90, 150, 140, 90]) # エラー
print('Kyogre: ' + str([100, 100, 90, 150, 140, 90]))
# Kyogre: [100, 100, 90, 150, 140, 90]
print('Dreams Come ' + True) # エラー
print('Dreams Come ' + str(True)) # Dreams Come True

5-6. イテラブルiterableからリストを生成して返す

list([iterable])
example.py
list(range(5)) # [0, 1, 2, 3, 4]
kyogre = {
    'H': 100,
    'A': 100,
    'B': 90,
    'C': 150,
    'D': 140,
    'S': 90
}
list(kyogre) # ['H', 'A', 'B', 'C', 'D', 'S'] 

5-7. イテラブルiterableからタプルを生成して返す

tuple([iterable])
example.py
tuple(range(5)) # (0, 1, 2, 3, 4)
tuple(kyogre) # ('H', 'A', 'B', 'C', 'D', 'S')

5-8. イテラブルiterable、マッピングmapping 2および**kwarg 3から辞書を作成して返す

5-8-1. 引数がひとつの場合

dict(**kwarg)
example.py
dict(h=100, a=100, b=90, c=150, d=140, s=90)
# {'h': 100, 'a': 100, 'b': 90, 'c': 150, 'd': 140, 's': 90}

このように、keyvalueの組み合わせから辞書を作りたいときに使える。

example.py
kyogre = {
    'H': 100,
    'A': 100,
    'B': 90,
    'C': 150,
    'D': 140,
    'S': 90
}
new_kyogre = dict(**kyogre)
print(new_kyogre)
# {'H': 100, 'A': 100, 'B': 90, 'C': 150, 'D': 140, 'S': 90}
print(id(kyogre)==id(new_kyogre))
# False

また、このようにimport copyせずに既存のオブジェクトをディープコピーした新しいオブジェクトを作りたいときにも使えそうではある。

5-8-2. 引数がふたつで第一引数がmappingの場合

dict(mapping, **kwarg)
example.py
debu_gabu = {
    'H': 10000008, # おかしい
    'A': 130,
    'B': 85,
    'C': 80,
    'D': 95,
    'S': 102
}
gabu = dict(debu_gabu, H=108)
print(gabu) # {'H': 108, 'A': 130, 'B': 85, 'C': 80, 'D': 95, 'S': 102}
print(id(debu_gabu)==id(gabu)) # False

第1引数に辞書、第2引数にkeyvalueの組み合わせを設定すると、既存の辞書の一部を変更した新しい辞書を作ることができる。

5-8-3. 引数がふたつで第一引数がiterableの場合

dict(iterable, **kwarg)
example.py
gabu = [('status', 600), ('weight', 95), ('height', 1900)]
modified_gabu = dict(gabu, height=190)
print(modified_gabu)
# {'status': 600, 'weight': 95, 'height': 190}

要素の更新に限らず、追加もできる。

6. 反復・並び替え

6-1. オブジェクトobjectからイテレータを生成する

iter(object)

6-2と同時に紹介

6-2. イテレータiteratorの次の要素を返す

next(iterator)
example.py
arr = ['a', 'b', 'c']
arr_iter = iter(arr)
next(arr_iter) # a
next(arr_iter) # b
next(arr_iter) # c
next(arr_iter) # エラー

6-3. イテラブルiterableから、enumerateオブジェクト4を返す

enumerate(iterable, start=0)
example.py
arr = ['a', 'b', 'c']
arr_enum = enumerate(arr, start=0)
next(arr_enum) # (0, 'a')
next(arr_enum) # (1, 'b')
next(arr_enum) # (2, 'c')
next(arr_enum) # エラー

6-4. 複数のイテラブル*iterablesから、タプルのイテレータを生成して返す

zip(*iterables)
example.py
pokes = ['Garchamp', 'Kyogre', 'Zapdos']
status = [600, 670, 580]
for poke, stat in zip(pokes, status):
    print(poke, stat)
# Garchamp 600
# Kyogre 670  
# Zapdos 580  

6-5. イテラブルiterableを並び替えてリストを返す。

keyには並び替えの順序を表す関数を指定し、省略時は要素を直接比較する
reverseTrueを設定した場合、比較結果を反転して並び替える

sorted(iterable, key=None, reverse=False)
example.py
arr = ['i', 'n', 'n', 'e', 'r', 'H', 'T', 'M', 'L']
sorted_arr = sorted(arr, reverse=False)
sorted_arr2 = sorted(arr, key=str.lower, reverse=False)
print(arr)
# ['i', 'n', 'n', 'e', 'r', 'H', 'T', 'M', 'L']
print(sorted_arr)
# ['H', 'L', 'M', 'T', 'e', 'i', 'n', 'n', 'r']
print(sorted_arr2)
# ['e', 'H', 'i', 'L', 'M', 'n', 'n', 'r', 'T']
# key=str.lowerによって大文字は小文字に直してソートするため、
# 大文字小文字を区別しないアルファベット順になっている。

リスト型のメソッドsort()とは別物。
sort()は元の配列をソートするのに対し、
組み込み関数であるsorted()はソートした新しい配列を返す。

7. ファイル

7-1. ファイルパスfileをファイルオブジェクトとして開く

各引数の説明

  • mode
    • ファイルを開くモード
  • encoding
    • 使用する文字コード
  • newline
    • ユニバーサル改行モードの動作を制御する
open(file, mode='r', encoding=None, newline=None)
example.py
file = open('C:/Users/user1/test.txt', mode='r')
print(file.read())
# testestest
file.close()

まとめ

疲れた!
何か誤字脱字や間違い、記事に書かれていない使用例などがございましたらご指摘してくださると助かります。

参考文献

  1. forで繰り返し可能なオブジェクト。リスト、タプル、集合、辞書、文字列など

  2. dict、辞書などと同じ意味らしい

  3. **について。こちらをご覧ください。
    https://qiita.com/ys_dirard/items/6009405b93c5c6ad335d

  4. デフォルトでは0となるstartからのカウントと、 iterable上のイテレーションによって得られた値を含むタプル。

3
6
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
3
6