Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Initializing Multiple Lists/Line

This is terribly ugly:

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

Is there a way to declare these variables on a single line?

like image 776
thenickname Avatar asked Mar 08 '10 16:03

thenickname


People also ask

How do you join multiple lists in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How do you initialize a list in Python?

To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension. The most common way to declare a list in Python is to use square brackets.

How do you split a list into smaller lists in Python?

Method #1: Using islice to split a list into sublists of given length, is the most elegant way. # into sublists of given length. Method #2: Using zip is another way to split a list into sublists of given length.


2 Answers

alist, blist, clist, dlist, elist = ([] for i in range(5)) 

The downside of above approach is, you need to count the number of names on the left of = and have exactly the same number of empty lists (e.g. via the range call, or more explicitly) on the right hand side.

The main thing is, don't use something like

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

nor

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

which would make all names refer to the same empty list!

like image 98
Alex Martelli Avatar answered Sep 24 '22 01:09

Alex Martelli


psData,nsData,msData,ckData,mAData,RData,pData = [],[],[],[],[],[],[] 
like image 24
YOU Avatar answered Sep 20 '22 01:09

YOU