0

i want to delete one item at a time from list but using remove(), pop() getting two items deleted.

Fruits = ['apple','hello','banana','lichi','mango']
for item in Fruits:
    print(item)
    Fruits.remove(item)

The answer i m getting is: apple banana mango

how to delete just one item from list.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
D Gupta
  • 9
  • 1

3 Answers3

0

The problem is that you're iterating over a list which you're removing items from at the same time.

for i in range(len(Fruit)):
  item = Fruit.pop()
  print(item)
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
Denis
  • 145
  • 1
  • 8
0
item = Fruits.pop()

to remove one item from the list

Fruits.remove('mango')

to remove 'mango' from the list

0

Try this?

Fruits = ['apple','hello','banana','lichi','mango']
while Fruits:
    print(Fruits.pop())

In your code sample, you can imagine that in the first loop, when 'apple' was removed from the list. the Fruits was changed to ['hello','banana','lichi','mango']. So, in the second loop, 'banana' was extracted and removed as the second item and 'hello' was bypassed. So, you know, avoid changing size of the list in for loop.

updated according to request:

Fruits = ['apple','hello','banana','lichi','mango']
i = 0
while i < len(Fruits):
    item = Fruits[i]
    print(item)
    if item == 'apple':
        Fruits.remove(item)
    else:
        i += 1

The for loop in Python does not like C/C++. It is actually transferred to go through the iterator. It is hard to be controlled precisely. So, while clause is used here. But while clause should be avoided because it is easy to cause dead loop.

xuemind
  • 405
  • 3
  • 11
  • thank you for your reply...but what if i want to delete a particular fruit say "banana" from the list ...and want to iterate through with remaining fruit list – D Gupta Dec 20 '18 at 04:24
  • thanks ...got a clue from your reply...it worked.... – D Gupta Dec 20 '18 at 05:31