Python: Walrus operator :=って何?

Last Updated on August 19, 2021 by shibatau



Walrus operatorを説明します。Walrus operatorは、Python 3.8以上で使用できます。



10 Cool Beginner Python Tricks That Will Make Your Life Easier

Walrus operator導入で大騒ぎになったということにびっくり。




(NAME := expression)

Nme: an identifier
expression: any valid un-parenthesized Python expression








次は、assignment statementです。何もプリントされません


assignment_statement = '尾身会長「若い人のせいじゃない、ウイルスの特徴' 


次は、assignment expressionです。文字列をプリントします。


(assignment_expression := '尾身会長「若い人のせいじゃない、ウイルスの特徴」')
# '尾身会長「若い人のせいじゃない、ウイルスの特徴」'




(assignment_expression := '尾身会長「若い人のせいじゃない、ウイルスの特徴」').replace("若い人", "菅首相")
# '尾身会長「菅首相のせいじゃない、ウイルスの特徴」'







# Without walrus operator
# 1
nums = [10, 20, 30, 40, 50]
if len(nums):
    print(f"There are {len(nums)} elements in the list")

# 2
nums = [10, 20, 30, 40, 50]
size = len(nums)
if size:
    print(f"There are {size} elements in the list")


Walrus Operatorを使うと次のようになります。上の1と行数は同じですが、sizeを実行すれば5の結果を得ることができます。


# using walrus operator
nums = [10, 20, 30, 40, 50]
if (size := len(nums)):
    print(f"There are {size} elements in the list")




There are 5 elements in the list 



About shibatau

I was born and grown up in Kyoto. I studied western philosophy at the University and specialized in analytic philosophy, especially Ludwig Wittgenstein at the postgraduate school. I'm interested in new technology, especially machine learning and have been learning R language for two years and began to learn Python last summer. Listening toParamore, Sia, Amazarashi and MIyuki Nakajima. Favorite movies I've recently seen: "FREEHELD". Favorite actors and actresses: Anthony Hopkins, Denzel Washington, Ellen Page, Meryl Streep, Mia Wasikowska and Robert DeNiro. Favorite books: Fyodor Mikhailovich Dostoyevsky, "The Karamazov Brothers", Shinran, "Lamentations of Divergences". Favorite phrase: Salvation by Faith. Twitter: @shibatau

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.