Home > database >  How to remove same entry from list after print in python
How to remove same entry from list after print in python

Time:01-27

failist = [123,234,345,456,567,678,789,890,901]

while len(failist) > 0:

    for x in range(len(failist)):
        print("Removing"   str(failist[x]))
        failist.remove(failist[x])

CodePudding user response:

It is not necessary to iterate by index.

failist = [123,234,345,456,567,678,789,890,901]

while failist:
    print('removing: ', failist[0])
    failist.remove(failist[0])

Output:

removing:  123
removing:  234
removing:  345
removing:  456
removing:  567
removing:  678
removing:  789
removing:  890
removing:  901

CodePudding user response:

Here is the best way to right the code you have in a concise manner.

failist = [123,234,345,456,567,678,789,890,901]
# while loop not necessary
for x in failist:
    print("Removing: ", x) # removed the concatenation and type cast
failist.clear() # clear list instead of removing one by one

CodePudding user response:

You should iterate using a copy of failist like in the example bellow:

failist = [123,234,345,456,567,678,789,890,901]

for number in failist[:]:
    print("Removing "   int(number))
    failist.remove(number)

the [:] operator creates a copy of your list so you can iterate and remove data from failist without missing any value.

  •  Tags:  
  • Related