LoginSignup
799

More than 3 years have passed since last update.

python 組み込み関数を全て(69個)紹介する

Last updated at Posted at 2019-10-24

はじめに

pythonに用意されている「組み込み関数」について、簡単な説明と使い方を記載します。
リファレンスとしてお使いいただければ幸いです。

本記事において組み込み関数とは公式ドキュメントに記載されている69個の関数と型を指します。

なお、各タイトルに番号が付いていますが、公式のものではありません。

検証環境

  • macOS Mojave 10.14.6
  • python 3.7.2
>>> import sys
>>> sys.version
'3.7.2 (default, Jan 13 2019, 12:50:01) \n[Clang 10.0.0 (clang-1000.11.45.5)]'

1. abs()

数の絶対値を返します。引数には整数、浮動小数点数、複素数を受け付けます。

>>> abs(10)
10
>>> abs(10.0)
10.0
>>> abs(-10)
10
>>> abs(complex(3,4))
5.0

2~3. all(), any()

  • all()は引数の要素が全てTrueならTrueを返し、一つでもFalseならFalseを返します。
  • any()は引数のいずれかの要素がTrueならTrueを返し、全てがFalseならFalseを返します。
>>> array = []

# 空の配列の場合、allはTrueになる
>>> all(array), any(array)
(True, False)

>>> array = [1,2,3]
>>> all(array), any(array)
(True, True)

# 0はFlase
>>> array = [0,1,2]
>>> all(array), any(array)
(False, True)

>>> array = [0,0,0]
>>> all(array), any(array)
(False, False)

>>> array = [True, True]
>>> all(array), any(array)
(True, True)

>>> array = [True, False]
>>> all(array), any(array)
(False, True)

>>> array = [False, False]
>>> all(array), any(array)
(False, False)

4~5. ascii(), repr()

共にeval()で評価すると引数と同じオブジェクトになる文字列を生成します。

  • ascii()は非ascii文字列をUnicodeでエスケープします。
  • repr()は非ascii文字列をエスケープしません。
>>> n = 1
>>> ascii(n), repr(n)  # 数値型に対する挙動は同じ
('1', '1')
>>> eval(ascii(n)), eval(repr(n))
(1, 1)

>>> s = '文字列'
>>> ascii(s), repr(s)  # 文字列型はasciiのみUnicodeエスケープされる
("'\\u6587\\u5b57\\u5217'", "'文字列'")
>>> eval(ascii(s)), eval(repr(s))
('文字列', '文字列')

6~8. bin(), oct(), hex()

  • bin()は整数を2進数文字列に変換します。
  • oct()は整数を8進数文字列に変換します。
  • hex()は整数を16進数文字列に変換します。
>>> bin(2), oct(2), hex(2)
('0b10', '0o2', '0x2')

>>> bin(-10), oct(-10), hex(-10)
('-0b1010', '-0o12', '-0xa')

>>> bin(2) + bin(-10), oct(2) + oct(-10), hex(2) + hex(-10)  # 文字列型なので+演算子は文字列結合として働く
('0b10-0b1010', '0o2-0o12', '0x2-0xa')

9. bool()

引数に対して、真理値判定手続きに基づいてTrueFalseを返します。

真理値判定手続きは少しややこしいですが、概ね以下のように判定されます。

  • False, 0, NoneFalse
  • 空のリスト、空文字列、空の辞書はFalse
  • 何か入っていればだいたいTrue
>>> bool()
False
>>> bool(None), bool(False), bool(0), bool([]), bool(''), bool({})
(False, False, False, False, False, False)
>>> bool(True), bool(1), bool([False]), bool('None'), bool({'key': None})
(True, True, True, True, True)

10. breakpoint()

該当の箇所からpython標準のデバッガを呼び出します。
デバッグに関しては以下が詳しいです。(pdbに関する部分)
PythonデバッグTips
上記参照先ではimport pdb; pdb.set_trace()としていますが、python3.7系からbreakpoint()で代用可能になっています。

>>> array = [1,2,3]
>>> total = sum(array)
>>> breakpoint()
--Return--
> <stdin>(1)<module>()->None
(Pdb) total
6

11~12. bytes(), bytearray()

共にbyte配列を返します。
文字列を引数に取る場合はbyte配列に変換するためのencoding方法を指定する必要があります。
なお、整数を引数に取る場合は指定した整数長の空byte配列を返します。

  • bytes()はimmutable(変更不可能)
  • bytearray()はmutable(変更可能)
>>> b1, b2 = bytes('abcde', encoding='utf-8'), bytearray('abcde', encoding='utf-8')
>>> b1, b2
(b'abcde', bytearray(b'abcde'))
>>> b1[0], b2[0]
(97, 97)

>>> b1[0] = 110  # immutableなので値の代入ができない
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> b2[0] = 110  # mutableなので値の代入ができる

>>> b1, b2
(b'abcde', bytearray(b'nbcde'))

>>> bytes(5), bytearray(5)  # 整数値を引数に取ると、空のバイトで初期化する
(b'\x00\x00\x00\x00\x00', bytearray(b'\x00\x00\x00\x00\x00'))

13. callable()

引数が呼び出し可能なオブジェクトであればTrueを、そうでなければFalseを返します。
なお、クラスは常に呼び出し可能で、インスタンスは__call__メソッドを持つ場合に呼び出し可能です。

>>> class CallableObject:
...     def __init__(self):
...             pass
...     def __call__(self, x):
...             return x ** 2
... 
>>> class NotCallableObject:
...     def __init__(self):
...             pass
... 
>>> callable(CallableObject), callable(NotCallableObject)  # クラス自体は呼び出し可能
(True, True)
>>> callable(CallableObject()), callable(NotCallableObject())  # インスタンスは__call__メソッドがあれば呼び出し可能
(True, False)

14~15. chr(), ord()

  • chrは整数を引数にとり、Unicodeのコードポイントが一致する文字を返します。
  • ordは文字を引数にとり、Unicodeのコードポイントを返します。
>>> chr(97)
'a'
>>> ord('a')
97
>>> chr(12354)
'あ'
>>> ord('あ')
12354

16~17. classmethod(), staticmethod()

  • classmethod()はクラス内で定義されている通常のメソッドをクラスメソッドに変換します。
  • staticmethod()はクラス内で定義されている通常のメソッドを静的メソッドに変換します。

クラスメソッド、静的メソッドの説明は以下のページが詳しいです。
Pythonで classmethod、staticmethod を使う

>>> class SampleObject:
...     def __init__(self):
...             self.name = 'sample object'
...     def normal_method(self):
...             print(self.name)
...             print(self.__name__)
...     @classmethod
...     def class_method(cls):
...             print(cls.__name__)
...     @staticmethod
...     def static_method():
...             print('static method')
... 

>>> SampleObject.normal_method()  # 通常のメソッドはクラスから呼べない
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: normal_method() missing 1 required positional argument: 'self'

>>> SampleObject.class_method()  # クラスから呼べる, __name__ が呼べる
SampleObject

>>> SampleObject.static_method()  # クラスから呼べる
static method

>>> SampleObject().normal_method()  # インスタンスからは呼べるがselfを引数に取るため __name__ は呼べない
sample object
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in normal_method
AttributeError: 'SampleObject' object has no attribute '__name__'

>>> SampleObject().class_method()  # インスタンスからも呼べる, __name__ が呼べる
SampleObject

>>> SampleObject().static_method()  # インスタンスからも呼べる
static method

18. compile()

引数をコードオブジェクトもしくはASTオブジェクトにコンパイルします。3つの引数が必須です。

  • source(文字列、ASTオブジェクト、バイト列)
  • filename(ファイル名あるいは<string>)
  • mode(一連の文ならexec, 単一の式ならeval, 単一の対話的文ならsingle)

文と式の違いについては以下が詳しいです。
Python3.8の新機能(2) - 代入式の導入
上記より引用させていただきます。

とっても乱暴に言ってしまうと、
文(Statement)は値を返さない
式(Expression)は値を返す


>>> statement = '''
... a = 5
... b = 3
... c = a + b
... '''
>>> code = compile(statement, '<string>', 'exec')

# execで文を実行する
>>> exec(code)
# 出力はされないが実行された変数がメモリ上に存在する
>>> a, b, c
(5, 3, 8)

# evalで式を評価する
>>> expression = 'a + b'
>>> code = compile(expression, '<string>', 'eval')
# 値が返却される
>>> eval(code)
8

19~21. int(), float(), complex()

  • int()は数値または文字列から作成された整数オブジェクトを返します。
  • float()は数または文字列から生成された浮動小数点数を返します。
  • complex()は文字列や数を複素数に変換します。
>>> int()  # 引数なしだと0
0
>>> int(10.5)  # 少数は切り捨て
10
>>> int(False), int(True)  # bool型を変換できる
(0, 1)

>>> float()
0.0
>>> float(False), float(True)
(0.0, 1.0)
>>> float('nan'), float('Infinity'), float('-infinity')  # 一部の文字列を受け付ける
(nan, inf, -inf)
>>> float('1e-003'), float('+1E6')
(0.001, 1000000.0)

>>> complex()
0j
>>> complex('1+2j')
(1+2j)
>>> complex(1,2)
(1+2j)
>>> complex(1)
(1+0j)

22~25. setattr(), getattr(), delattr(), hasattr()

  • setattr()はオブジェクトに値を設定します。引数はオブジェクト、文字列、任意の値です。
  • getattr()はオブジェクトの値を取得します。引数はオブジェクト、属性の名前です。
  • delattr()はオブジェクトの値を削除します。引数はオブジェクト、属性の名前です。
  • hasattr()はオブジェクトが属性を持っているかを確認します。引数はオブジェクト、属性の名前です。
>>> class SampleObject:
...     def __init__(self):
...             self.name = 'sample object'

>>> so = SampleObject()

>>> getattr(so, 'name')
'sample object'

>>> setattr(so, 'name', 'set attribute')
>>> getattr(so, 'name')
'set attribute'

>>> hasattr(so, 'name')
True

>>> delattr(so, 'name')

>>> hasattr(so, 'name')
False

>>> getattr(so, 'name')  # 削除されているのでエラーが発生する
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'SampleObject' object has no attribute 'name'

>>> getattr(so, 'name', 'No Attribute')  # 第三引数に属性がなかった場合の返り値を指定できる
'No Attribute'

26. dict()

組み込みクラスdictを作成します。

>>> dict()  # 引数なしで空の辞書を作成
{}
>>> dictionary = {'a': [1,2,3], 'b': None, 'c': '文字列'}
>>> dictionary['d'] = True
>>> dictionary
{'a': [1, 2, 3], 'b': None, 'c': '文字列', 'd': True}

27. dir()

引数がない場合、現在のスコープにある名前のリストを返します。
引数がある場合、そのオブジェクトの有効な属性のリストを返そうと試みます。

上記、公式ドキュメントを引用しています。
引数がある場合の記載が曖昧ですが、対話型での利用を前提としているため完全なリストを返すとは限らないようです。
とはいえ最重要な情報を返すように作成されているとのことですので、普段はそこまで気にしなくても良いかと思います。

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> a, b, c = 1, 2, 3
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c']

>>> [i for i in dir(list) if '_' not in i]  # list型がどのようなメソッドを持っているか調べる
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

28. divmod()

二つの(複素数以外の)数値引数を受け取り、除算結果の商と剰余を返します。

>>> divmod(10, 3)
(3, 1)
>>> divmod(10, 2)
(5, 0)
>>> divmod(10, 11)
(0, 10)
>>> divmod(10.0, 3.0)  # 浮動小数でも計算可能
(3.0, 1.0)

29. enumerate()

iterable(ループ可能)なオブジェクトを、オブジェクトの位置番号と要素のiterable(ループ可能な)オブジェクトに変換します。

>>> array = ['a', 'b', 'c', 'd']
>>> [(i, v) for i, v in enumerate(array)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

30~31. eval(), exec()

先述のcompile()の説明で登場しました。

  • eval()は与えられた文字列の式を評価します。返り値は式の評価結果です。
  • exec()は与えられた文字列の文を実行します。返り値はありません。(Noneです。)
>>> a, b = 5, 3
>>> eval('a + b')  # 返り値がある
8

>>> exec('a,b = 4, 6; c = a + b')  # 返り値はない
>>> c
10

>>> eval('c = a + b')  # 文は評価できない
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    c = a + b
      ^
SyntaxError: invalid syntax

32~33. filter(), map()

  • filter()は関数とiterable(ループ可能)なオブジェクトを引数に、関数の条件にマッチする要素だけを抽出したリストを返却します。
  • map()は関数とiterable(ループ可能)なオブジェクトを引数に、関数を適用した要素のリストを返却します。
>>> array = [0,1,2,3,4,5]
>>> list(filter(lambda x: x > 2, array)), list(map(lambda x: x * 2, array))
([3, 4, 5], [0, 2, 4, 6, 8, 10])

>>> list(filter(None, [0, 1, 2, 3, 4, 5]))  # 要素がFalseだと消える
[1, 2, 3, 4, 5]

# map()は引数を複数個取れる
>>> array1 = [1,2,3,4,5]
>>> array2 = [1,3,5,4,2]
>>> list(map(lambda x, y: int(x==y), array1, array2))
[1, 0, 0, 1, 0]

34. format()

第一引数の文字列を、第二引数のテンプレートでフォーマットした文字列を返却します。

フォーマット変換については以下が詳しいです。本記事では部分的に紹介します。
Python, formatで書式変換(0埋め、指数表記、16進数など)

>>> format('文字列')  # 引数なしだとそのまま
'文字列'
>>> format(100, '0>12d')  # 0埋め右詰12桁
'000000000100'
>>> format(10.3648573, '.4f')  # 有効数字4桁
'10.3649'
>>> format(168, 'X')  # 16進数化
'A8'

35~36. set(), frozenset()

組み込みクラスsetを返します。
- set()はmutable(変更可能)
- frozenset()はimutable(変更不可能)

>>> s1, s2 = set([1,1,2,3]), frozenset([1,1,2,3])
>>> s1, s2
({1, 2, 3}, frozenset({1, 2, 3}))

>>> s1.add(5), s2.add(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> s1, s2
({1, 2, 3, 5}, frozenset({1, 2, 3}))

>>> s1.remove(1), s2.remove(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'remove'
>>> s1, s2
({2, 3, 5}, frozenset({1, 2, 3}))

37~38. globals(), locals()


>>> def local_method():
...     n, s = 1, '文字列'
...     print('g variables', [(k, v) for k, v in globals().items() if '_' not in k])
...     print('l variables', [(k, v) for k, v in locals().items() if '_' not in k])

>>> n, s = 1000000, 'Global文字列'

# global空間ではglobals()とlocals()で取得できる変数は同じ
>>> print('g variables', [(k, v) for k, v in globals().items() if '_' not in k])
g variables [('n', 1000000), ('s', 'Global文字列')]

>>> print('l variables', [(k, v) for k, v in locals().items() if '_' not in k])
l variables [('n', 1000000), ('s', 'Global文字列')]

# メソッド空間ではglobals()とlocals()で取得できる変数が違う
>>> local_method()
g variables [('n', 1000000), ('s', 'Global文字列')]
l variables [('n', 1), ('s', '文字列')]

39. hash()

オブジェクトのハッシュ値を返します。
ハッシュ値は、値に対して一意に定められています。

>>> hash(1)
1
>>> hash(1.0)
1
>>> hash('a')
-4467320059549433340

40. help()

対話的使用に向けたヘルプシステムを起動します。
組み込み関数だけでなく、サードパーティ製のライブラリのドキュメントも確認することができます。


>>> import numpy as np
>>> help(np)
Help on package numpy:

NAME
    numpy

DESCRIPTION
    NumPy
    =====

    Provides
      1. An array object of arbitrary homogeneous items
      2. Fast mathematical operations over arrays
      3. Linear Algebra, Fourier Transforms, Random Number Generation

    How to use the documentation
    ----------------------------
# ~~~~~~~~~~~~~~~~~省略~~~~~~~~~~~~~~~~~~~~~~~~~~

41. id()

オブジェクトの識別子を返します。
識別子については以下が詳しいです。
Pythonの変数とオブジェクトについて

  • mutableな変数は値が変わっても識別子は変わらない
  • immutableな変数は値が変われば識別子も変わる
# 識別子は変わらない
>>> array1 = [1,2,3]
>>> id(array1)
4542258248
>>> array1[2] = 4
>>> id(array1)
4542258248

# 識別子が変わる
>>> n = 1
>>> id(n)
4425035920
>>> n = 2
>>> id(n)
4425035952

>>> array1 = [1,2,3]
# この記載は、同じ参照先をみることを意味する(別のメモリ空間にデータをコピーしているわけではない)
>>> array2 = array1
>>> id(array1), id(array2)
(4548004680, 4548004680)

# 一方の変更が二つの変数に影響する
>>> array1[2] = 10000
>>> array1, array2
([1, 2, 10000], [1, 2, 10000])

42. input()

引数があれば、標準出力にそれを出力します。その後、入力から1行を読み込んで返します。

>>> input('何か入力してください: ')
何か入力してください: abc
'abc'

43~44. isinstance(), issubclass()

  • isinstance()は第一引数にオブジェクト、第二引数にクラスをとり、オブジェクトがクラスのインスタンスかを判定します。
  • issubclass()は第一引数、第二引数にクラスをとり、第一引数が第二引数のサブクラスかを判定します。
>>> isinstance(1, int), isinstance(1.0, float), isinstance('string', str), isinstance(True, bool)
(True, True, True, True)
>>> isinstance(1, float), isinstance(1.0, int), isinstance('string', bool), isinstance(True, str)
(False, False, False, False)

# int はintのサブクラスであり、floatのサブクラスでなく、objectのサブクラス
>>> issubclass(int, int), issubclass(int, float), issubclass(int, object)
(True, False, True)

45~46. iter(), next()

  • iter()は引数が一つの場合、イテレータオブジェクトを返します。
  • iter()は引数が二つの場合は第一引数のオブジェクトを、第二引数の返り値を得るまで呼び出し続けます。
  • next()はイテレータオブジェクトの__next__メソッドを呼び出します。

イテレータオブジェクトは、__next__関数を持っており、これを呼び出すと要素を0から順番に取得することができます。
要素がなくなると、StopIteration例外をraiseします。

# next()と組み合わせて使う
>>> array = [1,2,3]
>>> it = iter(array)
>>> while True:
...     try:
...             print(next(it))
...     except StopIteration:
...             break
... 
1
2
3


# inputの返り値がexitになるまで入力を受け付け続ける
>> for _ in iter(input, 'exit'):
...     pass
... 
a
ba
e
exit
>>> 

47. len()

オブジェクトの長さあるいは要素の数を返します。
引数として受け取ることができるのは、文字列、バイト列、タプル、リスト、range()、辞書、集合です。

>>> len('ABC')
3
>>> len(['a', 'b', 'c'])
3
>>> len((1,2,3))
3
>>> len([1,2,3])
3
>>> 
>>> len({'a': 'apple', 'b': 'banana'})
2

48. list()

組み込みクラスlistを返します。

>>> list()
[]
>>> list('ABC')
['A', 'B', 'C']
>>> list((1,2,3))
[1, 2, 3]
>>> list({'a': 'apple', 'b': 'banana'})
['a', 'b']
>>> 

49~50. max(), min()

  • max()はiterable(ループ可能なオブジェクト)の中で最大の要素、または2つ以上の引数の中で最大のものを返します。
  • min()はiterable(ループ可能なオブジェクト)の中で最小の要素、または2つ以上の引数の中で最小のものを返します。

key引数で数値比較をする際に適用する関数を指定可能です。
default引数で空のlistが入力された際の返り値を指定可能です。


>> array = [1,2,3,4,5]
>>> max(array), min(array)
(5, 1)
>>> max(1,2,3,4,5), min(1,2,3,4,5)
(5, 1)
>>> max(array, key=lambda x: x % 4), min(array, key=lambda x: 10 - x)
(3, 5)

>>> max(list(filter(lambda x: x>10, array)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>> max(list(filter(lambda x: x>10, array)), default=-1)
-1

51. memoryview()

与えられたオブジェクトから作られたメモリビューオブジェクトを返します。
バッファプロトコルを利用しているため、bytes(), bytearray()よりも高速にバイナリデータを扱うことができます。

>>> v = memoryview(bytes('abcdefg', encoding='utf-8'))
>>> v[0]
97
>>> ord('a')
97

52. object()

特徴を持たない新しいオブジェクトを返します。
なお、objectは全てのクラスの基底クラスです。
この関数はいかなる引数も受け付けません。

53. open()

第一引数のファイルを第二引数のモード(デフォルトはrです)で開き、ファイルオブジェクトを返します。

# カレントディレクトリにabc.txtという名称のファイルを作り、ファイルオブジェクトを返す
>>> f = open('abc.txt', 'w')
>>> f.write('ABC\n')
4
>>> f.close()

# with構文でスコーピングすることでファイルを明示的にクローズする必要がなくなる
>>> with open('abc.txt') as f:
...     f.read()
... 
'ABC\n'

54. pow()

第一引数の第二引数乗を返します。
第三引数をとると、結果の剰余を高速に返します。

# 冪乗演算子と等しい
>>> pow(2, 10), 2 ** 10
(1024, 1024)

# 結果が等しいが左がより早い
>>> pow(2, 10, 10), 2 ** 10 % 10
(4, 4)

55. print()

受け取ったオブジェクトを(デフォルトでは標準出力に)出力します。
複数キーワードを受け取った場合はsep引数で区切りながら出力します。
end引数を指定すると最後に指定した文字列で終わります。(デフォルトは'\n')
file引数を指定するとファイル出力やエラー出力へも書き込みができます。

>>> print('ABC')
ABC

# 複数の引数を受け取れる. sepで結合し、endを最後に加える
>>> print('A', 'B', 'C', sep='/', end=' end\n')
A/B/C end

# ファイルオブジェクトを指定するとファイル出力できる
>>> with open('abc.txt', 'w') as f:
...     print('A', 'B', 'C', sep='/', end=' end\n', file=f)
... 
>>> 

56. property()

あるオブジェクトが持つ属性の振る舞いを決定するproperty属性を返します。
主にデコレータとして利用されます。

>>> class SampleObject:
...     def __init__(self):
...             self.__num = 100
...             self.word = 'camera'
... 
>>> so = SampleObject()
# 通常、「__」のプレフィックスがついた変数には外からアクセスできないため安全に使用できる
>>> so.__num
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'SampleObject' object has no attribute '__num'

# 普通の変数は当然アクセスできる
>>> so.word
'camera'

>>> class SampleObject:
...     def __init__(self):
...             self.__num = 100
...     @property
...     def num(self):
...             """It is the 'num' property"""
...             return self.__num
...     @num.setter
...     def num(self, num):
...             self.__num = num
...     @num.deleter
...     def num(self):
...             del self.__num
... 
>>> so = SampleObject()

# propertyが定義されていると、変数にアクセスできる
>>> so.num
100

# setterが定義されていると、変数を変更できる
>>> so.num = 150
>>> so.num
150

# deleterが定義されていると、変数を削除できる
>>> del so.num
>>> so.num
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in num
AttributeError: 'SampleObject' object has no attribute '_SampleObject__num'

# propertyにdocumentを記載が記載されていると、確認できる
>>> SampleObject.num.__doc__
"It is the 'num' property"

57. range()

第一引数から第二引数までの整数の連続値をiterable(ループ可能なオブジェクト)で返します。
第一引数はデフォルトでは0です。
なお、第三引数に、連続値の幅を指定できます。

>>> range(5)
range(0, 5)

# 可読性のためにlist型にcast
>>> list(range(5))
[0, 1, 2, 3, 4]

>> list(range(1, 5))
[1, 2, 3, 4]

>>> list(range(1, 5, 2))  # 1つ飛ばし
[1, 3]

58. reversed()

要素を逆順に取り出すイテレータオブジェクトを返します。

>>> array = [1,2,3,4,5]

# 返り値はイテレータオブジェクト
>>> rit = reversed(array)
>>> while True:
...     try:
...             print(next(rit))
...     except StopIteration:
...             break
... 
5
4
3
2
1

# 以下のように使うケースが多い
>>> for a in reversed(array):
...     print(a)
... 
5
4
3
2
1

59. round()

第一引数を第二引数の桁で丸めた値を返します。
四捨五入ではない点に注意してください

実際には偶数丸めが行われます。

端数が0.5より小さいなら切り捨て、
端数が0.5より大きいならは切り上げ、
端数がちょうど0.5なら切り捨てと切り上げのうち結果が偶数となる方へ丸める。

なおpython2系のround()は四捨五入です

>>> round(123.456, 1)  # 少数第一位で丸める
123.5
>>> round(123.456, -1)  # 十の位で丸める
120.0

>>> round(0.5), round(-0.5)  # 1ではなく0になる
(0, 0)
>>> round(1.5), round(-1.5)  # 2になる
(2, -2)
>>> round(2.675, 2)  # 浮動小数点は正確に表せないため、偶数丸めに当てはまらないケースもある
2.67

60. slice()

range()と同様に開始位置、終了位置、間隔の3つの引数をとります。
配列などのiterable(ループ可能なオブジェクト)に対して適用することで、該当位置の要素を取得できます。

>>> slice(1, 5, 2)
slice(1, 5, 2)

>>> array = [0,1,2,3,4,5]
>>> array[slice(1, 5, 2)]
[1, 3]

# 以下と等しい
>>> array[1:5:2]
[1, 3]

61. sorted()

iterable(ループ可能なオブジェクト)の要素を並べ替えた新たなリストを返します。
key引数を指定すると、指定したメソッドを適用した結果に対してソートすることができます。
reverse引数がTrueの場合、逆順ソートして結果を返します。

このソートは、同じ値の順序が元のリストと等しくなる安定ソートです。

>>> array = [3,4,2,1,5]

>>> sorted(array)
[1, 2, 3, 4, 5]
>>> sorted(array, reverse=True)
[5, 4, 3, 2, 1]
>>> sorted(array, key=lambda x: x % 3)  # 同じ値(4と1),(2と5)の順序が元のリストと変わらない安定ソート
[3, 4, 1, 2, 5]

62. str()

引数の文字列を返します。

>>> str(True), str(False)
('True', 'False')

>>> str(1), str(1.11), str(complex('1+2j'))
('1', '1.11', '(1+2j)')

>>> str([1,2,3])
'[1, 2, 3]'
>>> str((1,2,3))
'(1, 2, 3)'
>>> str({'a': 'apple', 'b': 'banana'})
"{'a': 'apple', 'b': 'banana'}"

>>> str(bytes('a', encoding='utf-8'))
"b'a'"

63. sum()

第一引数のiterable(ループ可能なオブジェクト)の要素を左から右へ合計し、総和を返します。
第二引数に初期値をとります。デフォルトは0です。

>>> array = [1,2,3,4,5]

>>> sum(array)
15
>>> sum(array, 6)
21

64. super()

親クラスのメソッドを呼び出します。


>>> class ParentObject:
...     def __init__(self):
...             self.num = 100
...             self.word = '文字'
... 
>>> class ChildObject(ParentObject):
...     def __init__(self):
...             try:
...                     print(self.num, self.word)
...             except AttributeError:
...                     print('親クラスの__init__内にある変数は参照できない')
...             super().__init__()
...             print(self.num, self.word)
... 
>>> co = ChildObject()
親クラスの__init__内にある変数は参照できない
100 文字


65. tuple()

tuple型を生成します。
タプルはimmutable(変更不可能)なシーケンスで、一般的に異種のデータの集まりを格納するために使われます。

>>> tuple()
()

>> tuple([1,2,3,1,'a','b','c'])
(1, 2, 3, 1, 'a', 'b', 'c')

>>> tuple('abc')
('a', 'b', 'c')

>>> t = ('abc')
>>> t[0]
'a'
>>> t[0] = 'z'  # 変更不能
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

66. type()

引数1つの場合は引数の型を返します。

引数3つの場合はクラスオブジェクトを返します。


>>> n = 10

# 以下、シンタックスハイライトが崩れるので出力のclassに_を追加しています。実際にはありません。
>>> type(n)
<class_ 'int'>

>>> type(n / 3)
<class_ 'float'>

>>> type(True)
<class_ 'bool'>

>>> type(True - 1)
<class_ 'int'>

# SampleObjectクラスを定義する
>>> SampleObject = type('SampleObject', (object,), dict(num=100))
>>> SampleObject.num
100

# 以下と同じオブジェクトが作られる
>>> class SampleObject:
...     num = 100
... 
>>> SampleObject.num
100

67. vars()

引数のオブジェクトが持つ属性のリストを返します。
引数なしの場合、locals()と同じ結果を返します。


>>> class SampleObject:
...     def __init__(self):
...             self.num = 100
...             self.word = '文字'
... 
>>> so = SampleObject()
>>> vars(so)
{'num': 100, 'word': '文字'}

>> a,b,c = 1,2,3
>>> [(k,v) for k,v in vars().items() if '_' not in k]
[('a', 1), ('b', 2), ('c', 3)]

>>> vars() == locals()
True

68. zip()

それぞれのイテラブルから要素を集めたイテレータを作ります。
長さの違うイテラブルを引数に与えた場合、短い長さに調整されるので注意が必要です。

>>> array1 = [1, 2, 3, 4, 5]
>>> array2 = ['a', 'b', 'c', 'd', 'e']
>>> for i, j in zip(array1, array2):
...     print(i, j)
... 
1 a
2 b
3 c
4 d
5 e
>>> 

>>> array3 = ['x', 'y', 'z']
>>> for i, j, k in zip(array1, array2, array3):
...     print(i, j, k)
... 
1 a x
2 b y
3 c z

69. __import__()

import文で呼び出される関数です。
直接使用することは推奨されていません。
通常のimport文では指定できない特殊な文字列(「-」等)を含むファイルをimportすることが可能ですが、
標準ライブラリのimportlib.import_module()が推奨されています。

終わりに

以上です。お疲れ様でした。
あまり細かい説明を記載するよりは実例ベースで紹介した方が
わかりやすいかなと思ったのですがいかがだったでしょうか。

皆様のお役に立てれば幸いです。

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
799