[Tutor] A shorter way to initialize a list?

Alan Gauld alan.gauld at btinternet.com
Wed Dec 14 01:28:57 CET 2011


On 13/12/11 20:39, Kaixi Luo wrote:

> I want to create a list of lists of lists (listB) from a list of lists
> (listA). Below there's a snippet of my code:
>
> listA = [[] for i in range(9)]
> listB = [[] for i in range(3)]

So list A containds 9 empty lists
And list B contains 3 empty lists

> count = 0
> for i in range(3):
>      for j in range(3):
>          listB[i].append(listA[count])
>          count+=1

And you want to add the 9 empty lists in A to the 3 empty lists in B to 
get a structure like:

listB = [
           [ [],[],[] ],
           [ [],[],[] ],
           [ [],[],[] ]
          ]

Is that it?

And in more general terms you want to create a list of len(B) sublists 
each of which holds len(A)/len(B) elements from A?
lets call the sizes La and Lb

Result = [ {...} for n in range(0,La,Lb)]
where {...} = listA[n:n+Lb]

So for your example:

 >>> A = [ [n] for n in range(9) ]
 >>> A
[[0], [1], [2], [3], [4], [5], [6], [7], [8]]

 >>> B = [ A[n:n+3] for n in range(0,9,3) ]
 >>> B
[ [[0], [1], [2]],
   [[3], [4], [5]],
   [[6], [7], [8]]]


The numbers just to help see which list goes where...

Now I could have miusunderstood.
Is that what you want?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list