Python - Initializing multiple lists / rows

This is terribly ugly:

psData = [] nsData = [] msData = [] ckData = [] mAData = [] RData = [] pData = [] 

Is there a way to declare these variables on the same line?

+60
python list initialization
Mar 08 '10 at 16:03
source share
7 answers
 alist, blist, clist, dlist, elist = ([] for i in range(5)) 

The disadvantage of the above approach is that you need to count the number of names to the left of = and have exactly the same number of empty lists (for example, by calling range or more explicitly) on the right hand side.

The main thing is not to use something like

 alist, blist, clist, dlist, elist = [[]] * 5 

neither

 alist = blist = clist = dlist = elist = [] 

in which all names will refer to the empty same list!

+141
Mar 08
source share
 psData,nsData,msData,ckData,mAData,RData,pData = [],[],[],[],[],[],[] 
+21
Mar 08 '10 at 16:05
source share

Depending on your needs, you might consider using defaultdict with a factory list. Something like:

 my_lists = collections.defaultdict(list) 

and then you can directly add my_lists ["psData"] and so on. This is the corresponding page of the document: http://docs.python.org/library/collections.html#collections.defaultdict

+9
Mar 08
source share

A slightly more efficient approach:

 alist, blist, clist, dlist, elist = ([] for _ in xrange(5)) 



[ NOTE ]:

  • xrange() is more optimal than range() in Python2. ( Link )

  • The variable i was unusable, so it is better to use _ . ( Link )

  • xrange() not defined in Python3.

+1
Oct 20 '18 at 7:28
source share

Mention that cleanliness can have performance implications. Calling a range function will slightly slow down the initialization process. Beware if you have any process that needs to reuse a variable many times.

 import time def r_init(): st=time.time() alist, blist, clist, dlist, elist = ([] for i in range(5)) et=time.time() print("{:.15f}".format(et-st)) def p_init(): st=time.time() alist=[];blist=[];clist=[];dlist=[];elist=[] et=time.time() print("{:.15f}".format(et-st)) for x in range(1,10): r_init() p_init() print("\n") 
0
Jan 13 '17 at 11:05
source share

You can use the class to initialize / store data, this will require more lines, but they can be easily read and more oriented to objects.

how

 class Data: def __init__(self): self.var1=[] <etc.> def zeroize(self): self.var1=[] <etc.> 

Then at the beginning at the beginning:

 data=Data() 

Then you can use a class in your loops or anywhere in the declaration of the main message.

 data.var1.append(varN) if(something): data.zeroize() 
-one
Jul 11 '12 at 17:12
source share

Something like

 alist, blist, clist, dlist, elist = ([],)*5 

would be the most elegant solution.

-one
Sep 14 '18 at 16:31
source share



All Articles