Answer the question
In order to leave comments, you need to log in
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)]
Answer the question
In order to leave comments, you need to log in
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]
array = [array[i] for i in range(len(array)) if len(array[i]) >= 2]
The question has been asked a bunch of times, so let's google it and learn something new.
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
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 questionAsk a Question
731 491 924 answers to any question