[Tutor] A shorter way to initialize a list?
Emile van Sebille
emile at fenx.com
Wed Dec 14 01:05:25 CET 2011
On 12/13/2011 3:26 PM Kaixi Luo said...
<snip>
> Uh, sorry. I made some very bad typos there. It should be:
>
> 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
>
This yields listB as [[[], [], []], [[], [], []], [[], [], []]]
So, the trick will be that each list element be unique. If you're not
careful, you'll get the same list elements. For example,
listB = [[[]]*3]*3
appears to yield the same result until you append to one of the elements
and discover one of the common early gotcha's:
>>> listB[1][1].append(1)
>>> print listB
[[[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]]]
To avoid this, each list container needs to be added separately, which
means that the two loops will be required.
You can express it as a single statement using list comprehensions:
>>> listB = [ [ [] for ii in range(3) ] for jj in range(3) ]
>>> listB
[[[], [], []], [[], [], []], [[], [], []]]
>>> listB[1][1].append(1)
>>> listB
[[[], [], []], [[], [1], []], [[], [], []]]
HTH,
Emile
More information about the Tutor
mailing list