0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの便利な書き方Tips集

Posted at

Pythonの便利な書き方Tips集

Pythonは可読性と簡潔さを重視した言語ですが、知っているとよりエレガントに書けるテクニックがあります。本記事では、少し玄人向けの便利な記法をいくつか箇所します。

アンパックと多重代入

Pythonでは、タプルやリストをアンパックして複数の変数に一度に代入できます。Qiitaの記事では、アンパックを用いて複数の値を同時に割り当てたり、余った値を*付き変数でまとめたりする例が紹介されています (qiita.com) 。この機能を使えばスワップやリストの分割が簡潔に書けます。

# 基本的なアンパック
a, b, c, d, e = (1, 2, 4, 8, 16)

# 先頭と末尾の値を取得し、残りをまとめる
a, *middle, e = (1, 2, 4, 8, 16)
# middle == [2, 4, 8]

比較演算子のチェーン

複数の比較を連続して書けるのもPythonの魅力です。例えば、2 <= x <= 8 のように書けば、xが2以上8以下かどうかを一つの式で表現できます (qiita.com) 。数直線のような条件を読み手にわかりやすく示せます。

x = 4
if 2 <= x <= 8:
    print("x is in range")

連鎖代入

複数の変数に同じ値を代入する場合、x = y = z = 2 のように書くことができます (qiita.com) 。アンパックと合わせて使うと柔軟に値を初期化できます。

x = y = z = 2  # すべての変数が2になる

Noneのチェックには is / is not

Noneと比較するときは == ではなく is または is not を使用するのがPythonicです (qiita.com) 。is 演算子はオブジェクトの同一性をチェックするため、意図しないバグを避けられます。

x = None
if x is None:
    print("x is None")

これらの記法を覚えておくと、Pythonコードをより簡潔に、読みやすく書けます。日々のコーディングに取り入れてみてください。

0
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?