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

1

1 Answer 1

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]

Sign up to request clarification or add additional context in comments.

2 Comments

wow, thanks a ton, it works like charm. Happy new year in Advance 🍺
@AmarjitSingh had to fix == to != in the rebuild the list. If no others answers help you out, check the mark next to my asnwer as answer please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.