Python独習!

習得したPython知識をペイフォワード

Pythonでリストの先頭だけを代入する(疑問あり)

リストの先頭の要素だけを変数に代入する方法として次の方法がある。
Pythonでタプルやリストをアンパック(複数の変数に展開して代入) | note.nkmk.me

#python 3.8.2
_list = [0, 1, 2, 3]

print(_list)
print(type(_list))

a, *b = _list      #先頭要素を a に、それより後を b に代入

print(a)
print(type(a))
print(b)
print(type(b))
---実行結果---
_list = [0, 1, 2, 3]
<class 'list'>
a = 0
<class 'int'>
b = [1, 2, 3]
<class 'list'>


一方で、アスタリスクの記述(上記では*b)を省略している例も見つけた。
Pythonでグラフ(Matplotlib)を表示して動的に変更する — 某エンジニアのお仕事以外のメモ(分冊)

h, = ax.plot([],[], 'green')

ちなみにax.plot([],[], 'green')はリスト型。

_plot = ax.plot([],[], 'green')
print(_plot)
print(type(_plot))
[<matplotlib.lines.Line2D object at 0x08F73BC8>]
<class 'list'>


では、以下も動くのかと思いきや、、エラーがでる。なぜだ…

_list = [0, 1, 2, 3]
a, = _list
print(a)
a, = _list
ValueError: too many values to unpack (expected 1)
/* -----codeの行番号----- */