LoginSignup
0
1

More than 1 year has passed since last update.

python 関数のアンパック

Last updated at Posted at 2022-12-12

関数の戻り値をアンパックしよう

関数の戻り値は、以下のコードのように、複数の変数に対してアンパックが可能。

exam.py
def func(numbers):
    max_num = max(numbers)
    min_num = min(numbers)
    return max_num, min_num


numbers = [4, 1, 6, 2, 10, 100, 5, 200]

max_num, min_num = func(numbers)
print(f'最大値:{max_num} 最小値{min_num}')

>>>最大値:200 最小値1

アスタリスクを用いたアンパック

例えば、リストの最大値と最小値だけを個別に変数に代入して、そのほかは一つの変数に代入することもできる。

exam2.py
def func(numbers):
    numbers.sort(reverse=True)
    return numbers


numbers = [4, 1, 6, 2, 10, 100, 5, 200]
max_num, *others, min_num = func(numbers)
print(f'最大値:{max_num} 最小値{min_num} その他{others}')

>>>最大値:200 最小値1 その他[100, 10, 6, 5, 4, 2]

複数の戻り値を返す際の注意

例えば以下のようなシチュエーションを考えてみる。

戻り値注意!
def func(numbers):
    ............
    return max_num, min_num, median_num, count, length

# max_numとmin_numが反対になっている。
min_num, max_num, median_num, count, length = func(numbers)

このように、多くの戻り値を返しすぎると、バグやヒューマンエラーのもとになりやすい。多くても3つ以内の戻り値にするのが、妥当だろう。

補足事項

アスタリスクを用いた場合は、listインスタンスを返すことになる。

exam3.py
numbers = [1, 2]
one, two, *other = numbers
print(one, two, other)

# *(アスタリスク)を用いると、listで返され、要素が残っていない場合は、空のリストを返す
>>>1 2 []

*(アスタリスク)を用いるとリストで返されるということは、リスト内のデータ量には注意が必要である。なぜなら、リストは格納されている要素すべてを返してしまうからだ。大量のデータがリスト内にあった場合、プログラムがクラッシュする危険をはらんでいる。メモリ以上のデータを扱わない確信がないときは、*(アスタリスク)は使うべきではない。

参考

Effective Python

python japan
https://www.python.jp/train/tuple/unpack.html

0
1
1

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
0
1