python *(アスタリスク)について

先日、コードを読んでいたところ、*(アスタリスク)がついた変数があり、pythonでもポインタがあるのか、と思ったところそうではなく、pythonでは違う使われ方をするので、まとめてみた。

アスタリスク1つの場合

掛け算の×

pythonで掛け算をする場合に使用。文字列、リスト、タプルにもOK

>>> 5*3
15
>>> '文字列も掛けられます' * 2
'文字列も掛けられます文字列も掛けられます'
>>> [1,2,3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> (1,2,3) * 4
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

>>> a = 5
>>> a *= 10
>>> print(a)
50
代入時の変数の数の可変長化

代入時に適当に可変長化してくれる

#以下では、代入のあまり部分を適当にリスト化してくれる
>>> i,j,*k=[1,2,3,4,5,6]
>>> print(i,j,k)
1 2 [3, 4, 5, 6]

#ちなみに以下では当たり前にエラー
>>> i,j,k=[1,2,3,4,5,6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)

#適当にやってくれる
>>> i,*j,k=[1,2,3,4,5,6]
>>> print(i,j,k)
1 [2, 3, 4, 5] 6

#関数の引数でも適当にやってくれる
>>> def f(*args):
...     print(args)
...
>>> f(1,2,3,4,5)
(1, 2, 3, 4, 5)
>>> f(1,"文字列",[0,1],(2,3,4))
(1, '文字列', [0, 1], (2, 3, 4))
パック化された変数をばらす(アンパッキング)

パック化された変数をばらしてくれる

#可変長化とは逆に、アンパックしたいときに*をつける
>>> l = (1,2,3,4,5)
>>> print(*l)
1 2 3 4 5
>>> l = [1,2,3,4,5]
>>> print(*l)
1 2 3 4 5

#変数でもできる
>>> def f(a,b,c):
...     print(f"{a}そして{b}さらに{c}")
...
>>> l = ('東京','大阪','名古屋')
>>> f(*l)
東京そして大阪さらに名古屋
>>>
>>> t = ['北海道','沖縄','長野']
>>> f(*t)
北海道そして沖縄さらに長野

アスタリスク2つの場合

累乗

累乗に使う。文字列、タプル、リストには使えない

>>> 5**2
25
>>> (2,4,6)**2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'
>>> [1,3,5]**3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
>>> '文字列'**2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

>>> n = 5
>>> n **= 3
>>> print(n)
125
関数の引数で辞書(Dictionary)化

関数の引数で変数とキーを与えると辞書化してくれる

>>> def f (**args):
...     print(args)
...
>>> f(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> f('あ'=4,'い'=5)
  File "<stdin>", line 1
    f('あ'=4,'い'=5)
      ^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
>>> f(ab=1,bc=2,cd=3)
{'ab': 1, 'bc': 2, 'cd': 3}

タイトルとURLをコピーしました