A
A
Art00052020-08-20 21:35:08
Python
Art0005, 2020-08-20 21:35:08

Why is it not working correctly?

a='a abc ccc cvv v'
b=a.split()
c=[]

for i in b:
    if len(i)>=3 and len(i)<=5:
        c.append(i)
        b.remove(i)

Why does [a, ccc, v] return to me and in c also without ccc
I look through the debug and for just jumps over ccc and doesn’t even take it in i, I don’t understand why

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
dmshar, 2020-08-20
@Art0005

If you need to "find and delete" at the same time, then you CAN do this only from the end of the list

a='a abc ccc cvv v'
b=a.split()
c=[]
for i in b[::-1]:
    if len(i)>=3 and len(i)<=5:
        c.append(i)
        b.remove(i)
print ( c)
print (b)

Result
['cvv', 'ccc', 'abc']
['a', 'v']

If you really want to - then you can do the reverse
c.reverse()
print ( c)

['cvv', 'ccc', 'abc']

S
Stanislav Pugachev, 2020-08-20
@Stqs

modifying the list while iterating over it is such an idea...

D
Dr. Bacon, 2020-08-20
@bacon

You don't have to change the object you are iterating over.

A
Art0005, 2020-08-20
@Art0005

I tried using range, but the same thing comes out

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question