Home > Net >  Way to check if a list exists after deleting it in Python
Way to check if a list exists after deleting it in Python

Time:06-20

I'm trying to see if there's a way I can see if the list got deleted after doing del command on the list

  del users
  if bool(users):
      print("exist")

One of the ways that I tried is mentioned above. But for each of these, I get an error-

UnboundLocalError: local variable 'users' referenced before assignment

Since the list is not present, it is unable to reference it but I wanted to know if there's a way(an in-built method) I can check if it got deleted( not empty)

CodePudding user response:

You can use a try-except statement to catch the error:

    test = [1, 2, 3]
    del test
    try:
        test
        print('Test exists!')
    except NameError:
        print("It's deleted!")
  • Related