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

More than 3 years have passed since last update.

[python] for 文の中で 配列.remove() をして要素を一部削除しようとしたが上手くいかなかった例

Last updated at Posted at 2021-05-02

見てもらった方が早いです。
違いは for 文で回す配列が aa.copy() かです。

上手くいかないコード
a = list(range(10))

for i in a:
    if i == 1:
        a.remove(1)
    elif i == 2:
        a.remove(2)

a
output
[0, 2, 3, 4, 5, 6, 7, 8, 9] # 2が削除されてない!
上手くいったコード
a = list(range(10))

# a.copy() にした
for i in a.copy():
    if i == 1:
        a.remove(1)
    elif i == 2:
        a.remove(2)

a
output
[0, 3, 4, 5, 6, 7, 8, 9] # 2が削除されている
0
0
2

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
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?