I've seen several answers about how to check if list is empty, but didn't find excatly what i need. shortly - in python, I need a way to check if list is full, and then empty it, but i need that the check will start just after i fill the list.
I'm define list by call my class - Packet()
class Packet(object):
"""description of class"""
def __init__(self):
self.newPacket = []
newPacket = Packet()
I have menu, which one of the options is to call function in the class to fill the list. but, if the function get chose again, i need to empty the instance, and start a new one. I've tried to do that:
if newPacket:
del newPacket
newPacket.MakePacket()
but this don't let me start the list by call the function.. if i disable the
if newPacket:
del newPacket
the function works just fine.
You appear to be confusing a particular Packet
instance that you have created and chosen to name newPacket
, with its attribute of the same name. Rather than delete the instance, or even delete the list, it sounds like you want to empty the list. Because you've given two different things the same name, the list in question is now accessible from your command-line as newPacket.newPacket
(although which the object itself likes to refer to it, in its own methods, as self.newPacket
).
So. When you del newPacket
, you are removing the reference to the object newPacket
from the current workspace. The interpreter will then raise a NameError
if you try to do anything with that symbol, such as newPacket.MakePacket()
- because that variable no longer exists in the current workspace.
If you want to implement Packet
methods that count the items in the self.newPacket
list attribute, or empty it, you could say:
class Packet(object):
# ...
def count( self ):
return len( self.newPacket )
def clear( self ):
del self.newPacket[:]
That incidentally illustrates one way of emptying a list, while retaining a reference to the now-empty list: del myList[:]