[Tutor] Fwd: A shorter way to initialize a list?

Rich Lovely roadierich at googlemail.com
Wed Dec 14 00:28:54 CET 2011


Forgot to reply all...


---------- Forwarded message ----------
From: Rich Lovely <roadierich at googlemail.com>
Date: 13 December 2011 23:17
Subject: Re: [Tutor] A shorter way to initialize a list?
To: Kaixi Luo <kaixiluo at gmail.com>


On 13 December 2011 20:39, Kaixi Luo <kaixiluo at gmail.com> wrote:
> Hello,
>
> 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:
>
> list1 = [[] for i in range(9)]
>
> # some code here...
>
> listA = [[] for i in range(3)]
> count = 0
> for i in range(3):
>     for j in range(3):
>         listB[i].append(listA[count])
>         count+=1
>
> My question is: is there any alternative way I can initialize listB without
> resorting to using 2 loops?
>
> I'm learning Python coming from a C++ background. So far, I've found that
> Python is an amazingly concise and expressive language. I just want to make
> sure I'm not being badly influenced by my old C++ habits.
>
> Cheers,
>
> Kaixi
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

I think it should read:

listA = [[] for i in range(9)]

# some code here...

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


So, you're partitioning list A into three, so [1,2,3,4,5,6,7,8,9]
becomes [[1,2,3],[4,5,6].[7,8,9]]

The easy way to do that is with slice notation;
>>> lst = [1,2,3,4,5,6,7,8,9]
>>> lst[0:3]

listB=[[] for i in range(3)]
for i, lst in enumerate(listB):
   startIndex = i*3
   lst.extend(listA[startIndex:startIndex+3])

This uses extend, which is the equivalent of your inner loop, and also
uses a more "pythonic" style; iterating over the list itself, or, if
you need numbers, an enumeration of the list, which returns a list (or
an iterable in python3) of (index, item) tuples.

There might be another way using fancy iterators, but that's something
for a latter email.
--
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10



By the way, the fancy iterator method is;

from itertools import izip

it = iter(listA)
listB = [[] for i in range(3)]
for b, i in izip(listB, izip(it, it, it)):
    b.extend(i)

(Sorry, I enjoy this sort of thing a little too much.)
-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10


More information about the Tutor mailing list