2
0

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】集合の初期化に気を付けたい

Posted at

早速ですが以下を見てみてください

>>> s = {1, 2, 3, 4}
>>> type(s)
<class 'set'>
>>> s = {}
>>> type(s)
<class 'dict'>

上記のように、s = {} で集合を初期化しようとすると、
type() で確認した際に 最初のset ではなく dict(辞書型)と表示されます。

これは うっかりミスが起きやすいPythonの文法上の落とし穴 で、
{} は「空の辞書」を表すリテラルとして予約されているためです。
集合として初期化したい場合は、以下のように書く必要があります。

s = set()

このようにすれば、正しく空の集合(<class 'set'>)として扱われます。


細かい点ですが、初期化時のこの違いを理解していないと
「集合のはずが辞書になっていた」というミスに繋がります。

気を付けましょう(自戒)

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?