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?

More than 1 year has passed since last update.

Pythonの破壊的,非破壊的な操作

Posted at

破壊的な操作

破壊的な操作とは,元のオブジェクト自体を変更する操作のことです.元のオブジェクトの内容が変更され,元の状態を保持しません.

例1:append()

# 破壊的な操作の例
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 出力: [1, 2, 3, 4]

appendは,もとのリスト(my_list)自体を壊し,数を追加しています.
my_list.append(4)が行われた時点で,もうmy_listはもとの状態と同じではないのです.

例2 sort()

# 破壊的な例:sort()メソッド
my_list=[9,3,5,1]

my_list.sort()

print(my_list) # 出力 [1, 3, 5, 9]

もとのリストを変更しているので,破壊的な操作です.

非破壊的な操作

指定した操作を行っても,もとのオブジェクトの原型はとどめる操作です.

例1:+演算子

original_list = [1, 2, 3]
new_list = original_list + [4]
print(original_list)  # 出力: [1, 2, 3]
print(new_list)       # 出力: [1, 2, 3, 4]

例2:sorted()

# 非破壊的な例:sorted()メソッド
my_list=[9,3,5,1]

sorted_list=sorted(my_list) 

print(my_list) # 出力[9, 3, 5, 1]
print(sorted_list) # 出力[1, 3, 5, 9]

もとのリストは変更(破壊)されていないことが分かります.

復習

最後に問題です.
こちらは,破壊的でしょうか,それとも非破壊的でしょうか.

my_list=[9,3,5,1]

my_list.pop(0)

print(my_list) 

ちなみに,pop(0)は,0番目の要素を削除します.

答えはこちら↓

答え 

破壊的な操作です.
出力は,

[3, 5, 1]

となります.

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?