in python, how to check if list is not empty, and empty it if so? -


i've seen several answers how check if list empty, didn't find excatly need. shortly - in python, need way check if list full, , empty it, need check start after fill list.

i'm define list call class - packet()

class packet(object): """description of class"""     def __init__(self):         self.newpacket = [] newpacket = packet() 

i have menu, 1 of options call function in class fill list. but, if function chose again, need empty instance, , start new one. i've tried that:

if newpacket:     del newpacket newpacket.makepacket() 

but don't let me start list call function.. if disable

if newpacket:     del newpacket 

the function works fine.

you appear confusing particular packet instance have created , chosen name newpacket, attribute of same name. rather delete instance, or delete list, sounds want empty list. because you've given 2 different things same name, list in question accessible command-line newpacket.newpacket (although object likes refer it, in own methods, self.newpacket).

so. when del newpacket, removing reference object newpacket current workspace. interpreter raise nameerror if try symbol, such newpacket.makepacket() - because variable no longer exists in current workspace.

if want implement packet methods count items in self.newpacket list attribute, or empty it, say:

class packet(object):      # ...      def count( self ):         return len( self.newpacket )      def clear( self ):         del self.newpacket[:] 

that incidentally illustrates 1 way of emptying list, while retaining reference now-empty list: del mylist[:]


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -