質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

1351閲覧

Pythonにおける「ist ndex out of range」への対処

NaokiHirose

総合スコア9

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2018/08/03 05:04

前提・実現したいこと

ここに質問の内容を詳しく書いてください。
(例)PHP(CakePHP)で●●なシステムを作っています。
■■な機能を実装中に以下のエラーメッセージが発生しました。

発生している問題・エラーメッセージ

--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-82-ae76bf4842a6> in <module>() ----> 1 print(remove_evenindex(["a", "b", "c", "d", "e", "f", "g"]) == ['b', 'd', 'f'] ) 2 print(remove_evenindex([1, 2, 3, 4, 5]) == [2, 4]) <ipython-input-81-73cce9575198> in remove_evenindex(ln) 1 def remove_evenindex(ln): 2 for j in range(0,len(ln),2): ----> 3 ln.remove(ln[j]) 4 return ln IndexError: list index out of range

def remove_evenindex(ln):

for j in range(0,len(ln),2): ln.remove(ln[j]) return ln
Python

試したこと

for j in range(0,len(ln),2)

for j in range(1,len(ln),2)
にして、

def remove_evenindex(ln):
ln2 = []
for j in range(1, len(ln), 2):
ln2.append(ln[j])
return ln2

でコードを書けば、問題なくできます。
なぜ「list ndex out of range」となってしまうのでしょう。

補足情報(FW/ツールのバージョンなど)

プログラミング自体、初めて3日目の初心者です。
どうか、皆様のお知恵で、初心者でも理解できるレベルでご説明頂ければ幸いです。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

なぜ「list ndex out of range」となってしまうのでしょう。

実際に値を覗いてみると良いです。

Python

1def remove_evenindex(ln): 2 for j in range(0,len(ln),2): 3 print(f'I will remove {j}th elem from {ln}') 4 ln.remove(ln[j]) 5 return ln 6 7remove_evenindex(["a", "b", "c", "d", "e", "f", "g"])

実行結果 Wandbox

Python

1I will remove 0th elem from ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 2I will remove 2th elem from ['b', 'c', 'd', 'e', 'f', 'g'] 3I will remove 4th elem from ['b', 'c', 'e', 'f', 'g'] 4I will remove 6th elem from ['b', 'c', 'e', 'f'] 5Traceback (most recent call last): 6 File "prog.py", line 7, in <module> 7 remove_evenindex(["a", "b", "c", "d", "e", "f", "g"]) 8 File "prog.py", line 4, in remove_evenindex 9 ln.remove(ln[j]) 10IndexError: list index out of range

リスト長がどんどん短くなりますが、その都度 len(ln) を再計算してはくれないのです。
ループ対象のデータをいじると、しばしばこのような問題を引き起こします。

解決策

NaokiHiroseさんの書かれたコードのように、新たにリストを作るのが簡単です。
これならば元のリスト長は変化しません。


なお、スライスを使うと次のように簡潔に書けます。

Python

1def remove_evenindex(ln): 2 return ln[1::2]

投稿2018/08/03 05:10

編集2018/08/03 05:29
LouiS0616

総合スコア35660

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

NaokiHirose

2018/08/03 05:33

物凄く分かりやすい回答を、しかも迅速にくださりありがとうございました。 駆け出しの私でも一瞬で理解できるほど、分かりやすいものでした。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問