[Tutor] packing a list of lists

Michael M Mason michael at shamirlens.co.uk
Fri Aug 28 17:23:48 CEST 2009


Kevin Parks wrote: 
> def pack(in_seq):
> 	out_list=[]
> 	x = 1
> 	ll=[1, 1]
> 	for each in in_seq:
> 		ll[0] = x
> 		ll[1] = each
> 		out_list.append(ll)
> 		#print ll
> 		x = x + 1
> 	print out_list

Variable out_list consists of list ll repeated however many times. Each
time you change ll you're changing it everywhere it appears in out_list.
That is, what's being appended to out_list isn't a copy of ll, it's a
pointer to ll.

You need something like:-

        out_list.append([ll[0],ll[1]])

And you need to add a return at the end of the function, otherwise it
returns None:

	return out_list

-- 
Michael


More information about the Tutor mailing list