0

I have a list and want to remove the third sublist, but I am not able to

import time

def mylist():
    active_clients.append([1,10])
    active_clients.append([1, 20])
    active_clients.append([1, 30])

    print " \n before deleting"
    for t in active_clients:

        print t[0], t[1]

        if (t[1] == 30):
            del t


    print "\n after deleting"
    for a in active_clients:

        print a[0], a[1]



if __name__ == '__main__':
    active_clients = []
    mylist()

How can I get output like

before deleting

1 10

1 20

1 30

after deleting

1 10

1 20

Amarjit Dhillon
  • 2,718
  • 3
  • 23
  • 62
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – Patrick Artner Dec 29 '17 at 22:10

1 Answers1

1
import time

def mylist():
    global active_clients
    active_clients.append([1,10])
    active_clients.append([1, 20])
    active_clients.append([1, 30])

    toRemove = [] # remember what to remove
    print " \n before deleting"
    for t in active_clients:

        print t[0], t[1]

        if (t[1] == 30):
            toRemove.append(t) # remember

    for t in toRemove: # remove em all
        active_clients.remove(t)

    print "\n after deleting"
    for a in active_clients:

        print a[0], a[1]



if __name__ == '__main__':
    active_clients = []
    mylist()

Or rebuild the list: active_clients = [x for x in active_clients if x[1] != 30]

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69