足し算のリスト・辞書・文字列での挙動【Python】

pythonの足し算のアイキャッチPython

足し算(+演算子)は数値同士でよく使いますが、リストや辞書、文字列での足し算はどのような動作をするか知っていますか?

今回はリスト・辞書・文字列での足し算(+演算子)の挙動を紹介していきます。

リスト

リストで+演算子を使うと、リストが結合されます。extend()と似たような動作ですね。
+は新たなリストを返し、extend()は既存のリストに対して結合します。

x=[1,2,3]
y=[4,5,6]

print(x+y)
# [1, 2, 3, 4, 5, 6]

x=[1,2,3,[0]]
y=[4,5,6]

print(x+y)
# [1, 2, 3, [0], 4, 5, 6]
x=[1,2,3]
y=[4,5,6]

x.extend(y)
print(x)
# [1, 2, 3, 4, 5, 6]

辞書

タイトルに辞書を入れたのは引っ掛けみたいな感じになってしまいますが、実は辞書で足し算するとエラーになります。
直感的にはリストのように結合されると考えていましたが、結合はupdate()で可能なようです。

dict1 = {'apple':100,'banana':30}
dict2 = {'orange':50}

print(dict1+dict2)
# TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
dict1 = {'apple':100,'banana':30}
dict2 = {'orange':50}
dict1.update(dict2)

print(dict1)
# {'apple': 100, 'banana': 30, 'orange': 50}

文字列

文字列で足し算(+演算子)を使うと、文字列同士が結合されて新たな文字列が返されます。

s1 = 'you are'
s2 = 'genius!'

print(s1 + s2)
# you aregenius!

足し算以外の結合方法としては''.join([文字列1,文字列2,…])というのもあります。

s1 = 'you are'
s2 = 'genius!'

print(''.join([s1,s2]))

コメント