V
V
Vasily Nikonov2020-01-01 19:00:13
Python
Vasily Nikonov, 2020-01-01 19:00:13

Array formatting works very strangely. Where is the mistake?

I am forming an array in which there are "extra" elements, they, as a rule, contain only one element or are completely empty.
I take an array element, check how long it is, and if the number of elements in it is strictly less than two, then this element is removed. My code (sorry if it's not perfectly "Pythonic" -- just starting to learn Python) looks something like this:

for item in array:
  if len(item) <= 2:
    del array[array.index(item)]

The problem is that if I have two consecutive unnecessary elements, then it will only remove one. Please tell me what is the problem and how to fix it. Thank you.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrey Ezhgurov, 2020-01-01
@jintaxi

Since you are removing elements from an array, you must move from the end of the array to its beginning. And it's better by indexes, not by elements.

for i in range(len(array), -1, -1):
  if len(array[i]) <= 2:
    del array[i]

If you do it in the style of the proposed second question of the option, then it will be more efficient:
array = [array[i] for i in range(len(array)) if len(array[i]) >= 2]

D
Dr. Bacon, 2020-01-01
@bacon

The question has been asked a bunch of times, so let's google it and learn something new.

W
Wataru, 2020-01-01
@wataru

You can't delete or add items inside . The iteration crashes. There are many examples of how to do it differently in here . for item in array

V
Vasily Nikonov, 2020-01-01
@jintaxi

If suddenly someone stumbles upon this question and the answer is important to him, then this code solves this problem:

array = [item for item in array if len(array[array.index(item)]) >= 2]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question