41
38

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の組み込み関数でこれあったんだ10選

Posted at

Pythonには組み込み関数が豊富にあり、現時点で71個あります。

もしかすると「これ組み込み関数であったんだ」みたいな人がいるかもしれないと思って、今回は10個ピックアップさせていただきました。

1つでも新しい知見があると幸いです。

それではいってみましょう!

slice(start, stop, step)

個々の要素を取得する操作をインデックスと言い、ある部分(始点と終点)を選択して取得する操作をスライスと言いますが、

In
word = "Python"

# インデックス
print(word[0])
print(word[5])

# スライス
print(word[1:5])
print(word[-6:-1])
Out
P
n
ytho
Pytho

slice関数を使うと、容易に同じ位置の要素を繰り返し取得できます。

In
name_list = ["山田様", "田中様", "鈴木様", "林様", "長谷川様"]
sl = slice(-1)

for name in name_list:
    print(name[sl])
Out
山田
田中
鈴木
林
長谷川

divmod(a, b)

Pythonには割り算の商と余りを取得するdivmod関数があります。Pythonでは、//で整数の商、%で余りを算出できますが、両方欲しいときはdivmod関数の方が便利です。

In
print(divmod(11, 5))

q , mod = divmod(11, 5)
print(q)
print(mod)
Out
(2, 1)
2
1

abs(x)

abs関数は数の絶対値を返します。

288ef84237a8-20250104.png

In
print(abs(3))
print(abs(-5))
Out
3
5

math.fabs(x)

math.fabs()でも絶対値を取得することができます。
ただし、mathモジュールは明示的な注記のない限り、戻り値は全て浮動小数点数となります。

In
import math

print(math.fabs(1))
print(math.fabs(-1.0))
Out
1.0
1.0

all(iterable)

iterableの全ての要素が真ならば (もしくはiterableが空ならば) Trueを返します。

イテラブルはfor文で繰り返し可能なオブジェクト(list, tuple, strなど)です。

In
print(all([True, True]))
print(all([True, False]))
print(all([]))
Out
True
False
True

以下は偽と判定される主な組み込みオブジェクトです:
偽であると定義されている定数: None と False
数値型におけるゼロ: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
空のシーケンスまたはコレクション: '', (), [], {}, set(), range(0)
真理値判定

any(iterable)

iterableのいずれかの要素が真ならばTrueを返します。iterableが空ならFalseを返します。

In
print(any([True, True]))
print(any([True, False]))
print(any([]))
Out
True
True
False

上述のallと一緒にまとめると以下のようになります。

関数 意味
all(iterable) 全要素が真かどうか
any(iterable) 真な要素があるかどうか
not all(iterable) 全要素が偽かどうか
not any(iterable) 偽な要素があるかどうか

filter(function, iterable)

イテラブル(リストやタプルなど)から条件を満たす要素を抽出できます。

In
def even_num(x):
    return x % 2 == 0

result = filter(even_num, [0, 1, 2, 3, 4])

for item in result:
    print(item)
Out
0
2
4

dir(object)

dir関数は内容確認に便利です。

In
print(dir(list))
Out
['__add__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

引数無しの場合

引数無しの場合は、現在のローカルスコープで定義されている名前を確認することができます。

>>> a = 5
>>> def func():
...     b = 9
...
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'func']

スコープとは、変数の有効範囲です。

breakpoint

breakpointはPythonに標準でついているデバッガーです。breakpointを使用するとコードを1行ずつ実行することができ、変数の確認に役立ちます。

デバッガーとはバグを見つけるツールで、デバッグはバグの原因を探して取り除く作業です。
e5f28ed0cb27-20250106.png

コマンド 説明
p(rint) 変数の値を表示
n(ext) 1行実行して、次の行へ(関数の中には入らない)
s(tep) 1行実行して、次の行へ(関数の中には入る)
r(eturn) 現在の関数が返るまで実行
c(ontinue) 次のbreakpointに移動
q(uit) デバッグを終了する

50842085f420-20241230.png

enumerate(iterable)

enumerate関数は、要素のインデックスと要素を同時に取り出すことができます。

a2bdec1f10d6-20250108.png

In
color_list = ["red", "yellow", "blue"]

for i, color in enumerate(color_list):
    print(i, color)
Out
0 red
1 yellow
2 blue

callable(object)

Pythonでは関数やメソッドのことを呼び出し可能オブジェクトと言いますが、そのオブジェクトが呼び出し可能かどうかを調べるときにcallable関数を使用することができます。

In
import random

def func():
    pass

print(callable(func))
print(callable(random.random))
print(callable(1))
Out
True
True
False

おわり

最後までお読みいただきありがとうございました。
組み込み関数を知らないとコードが冗長になったり、可読性が低下したりするので、きちんと押さえておきましょう。

組み込み関数を学べる書籍を出してます。
良かったら活用してね!

41
38
2

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
41
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?