Pythonでは、データ型は可変または不変のいずれかに分類できます。可変データ型は、作成後に変更できるデータ型です。これは、新しいオブジェクトを作成することなくコンテンツを変更できることを意味します。一方、不変のデータ型は、作成されると変更できないデータ型です。不変のタイプを変更するように見える操作は、実際に新しいオブジェクトを作成することになります。
Pythonの可変データ型の例は次のとおりです。
説明するコードの例を次に示します。
<code class="python"># Lists my_list = [1, 2, 3] my_list.append(4) # Modifying the list print(my_list) # Output: [1, 2, 3, 4] # Dictionaries my_dict = {'a': 1, 'b': 2} my_dict['c'] = 3 # Adding a new key-value pair print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3} # Sets my_set = {1, 2, 3} my_set.add(4) # Adding an element print(my_set) # Output: {1, 2, 3, 4} # Byte Arrays my_bytearray = bytearray(b'hello') my_bytearray[0] = 72 # Modifying the first byte print(my_bytearray) # Output: bytearray(b'Hello')</code>
Pythonの特定のデータ型の不変性は、いくつかの方法でプログラミングに影響します。
ハッシュ性の問題を示す例を以下に示します。
<code class="python"># Immutable (hashable) my_tuple = (1, 2, 3) my_dict = {my_tuple: 'value'} print(my_dict) # Output: {(1, 2, 3): 'value'} # Mutable (not hashable) my_list = [1, 2, 3] # This will raise a TypeError # my_dict = {my_list: 'value'}</code>
Pythonで可変データ型と不変のデータ型を使用することのパフォーマンスへの影響は、次のように要約できます。
パフォーマンスの違いを示すコード例を次に示します。
<code class="python">import timeit # Mutable: Appending to a list mutable_time = timeit.timeit('l = [1, 2, 3]; l.append(4)', number=1000000) print(f"Time to append to a list: {mutable_time}") # Immutable: Creating a new tuple immutable_time = timeit.timeit('t = (1, 2, 3); t = t (4,)', number=1000000) print(f"Time to create a new tuple: {immutable_time}")</code>
この例では、リストへのAppending(Mutable操作)は、一般に新しいタプル(不変の操作)を作成するよりも速いです。ただし、実際のパフォーマンスの違いは、特定のユースケースと実行中の操作のスケールに基づいて異なります。
以上がPythonの可変で不変のデータ型とは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。