知ってると便利かも知れないPythonの組み込み関数

Pythonの数ある組み込み関数の中から、Python初学者向けに知ってるとコードを書く時に便利かも知れない組み込み関数をいくつかご紹介

dir

https://docs.python.org/ja/3/library/functions.html#dir

オブジェクトの持つ属性の名前を文字列のリストで返してくれる関数。

文字列(str)に対して実行するとこんな感じ

dir("string")
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
# '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
# '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
# 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower','isnumeric',
# 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex',
# 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

enumerate

https://docs.python.org/ja/3/library/functions.html#enumerate

インデックス付きループを簡単に作れる。

lst = ["a", "b", "c"]
for i, c in enumerate(lst):
  print(i, "," , c)
# 0 , a
# 1 , b
# 2 , c

第一引数に反復可能オプジェクトを渡す。
第二引数に整数(int)を渡すことでその値からインデックスを開始できる。

lst = ["a", "b", "c"]
start_index = 5
for i, c in enumerate(lst, start_index):
  print(i, "," , c)
# 5 , a
# 6 , b
# 7 , c

zip

https://docs.python.org/ja/3/library/functions.html#zip

複数の反復可能オブジェクトを同時にループで回せる。

lst1 = [0, 1, 2, 3, 4]
lst2 = [5, 6, 7, 8, 9]

for i, j in zip(lst1, lst2):
    print(i, "," , j)
# 0, 5
# 1, 6
# 2, 7
# 3, 8
# 4, 9

要素数が違う場合、一番短いものの長さに合わせられる。

lst1 = [0, 1, 2, 3, 4]
lst2 = [5, 6, 7, 8, 9]
lst3 = [10, 11]
for i, j, k in zip(lst1, lst2):
    print(i, "," , j, ",", k)
# 0, 5, 10
# 1, 6, 11

type

https://docs.python.org/ja/3/library/functions.html#type

オブジェクトの型を調べることができる関数

type(1) # <class 'int'>
type(0.1) # <class 'float'>
type("s") # <class 'str'>
type([]) # <class 'list'>
type({}) # <class 'dict'>

変数に入っている値の型を調べる時に役立つ

isinstance

https://docs.python.org/ja/3/library/functions.html#isinstance

オブジェクトの型をが一致するかを調べることができる関数。

第一引数のオブジェクトが第二引数のインスタンス、またはサブクラスのインスタンスであればTrueを返す。

isinstance(1, int) # True
isinstance(1, str) # False
isinstance("python", str) # True
isinstance("python", int) # False
isinstance(True, bool) # True
isinstance(True, int) # True  ※bool型はint型のサブクラスなのでTrue

型によって処理を分けたい時に便利。

さいごに

知っているとPythonの学習が捗りそうな組み込み関数(dir, enumerate, zip, type, isinstance)を紹介してみました。

他にも便利な組み込み関数がたくさんあるので興味のある人は

https://docs.python.org/ja/3/library/functions.html

を読むときっと幸せになれます。

以上、知ってると便利かも知れないPythonの組み込み関数の紹介でした。