[Tutor] Creating a list from other lists

Walter Prins wprins at gmail.com
Mon Oct 22 12:34:47 CEST 2012

Hi Saad,

On 22 October 2012 11:21, Saad Javed <sbjaved at gmail.com> wrote:
> Hi,
> I'm trying to create a list (L) from items of different lists (a, b, c) but
> in a specific order (L = [[a1, b1, c1], [a2, b2, c2]...etc])
> L = []
> a = [1, 2, 3, 4]
> b = ['a', 'b', 'c', 'd']
> c = [2009, 2010, 2011, 2012]
> for x, y , z in zip(a, b, c):
> L.extend([x, y, z])
> print L
> But this outputs:
> [[1, 'a', 2009]]
> [[1, 'a', 2009], [2, 'b', 2010]]
> [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011]]
> [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd', 2012]]
> I just want L = [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd',
> 2012]]

You've already asked essentially this question on another thread -- in
general please don't start new threads for the same question but
continue the discussion on the original question for the sake of
continuity and avoiding wasting people's time.  (New readers of the
new question may not be aware of the previous discussion, and may
expend time and energy addressing issues which have already been
discussed in the previous question.)

As for your problem: You're printing the list every iteration of the
loop which is why your output looks the way it does.   Instead put
your print statement after the loop and you'll see the list you get
after the loop is in fact what you say you want.

However, that doesn't actually solve your problem, because you're
putting the input data into the lists in sorted order already.  You
should jumble up your input data to ensure you also solve the sorting
aspect of this problem (or use the input data from your original
problem which was jumbled up enough already.)

Hint, to deal with sorting your output list, refer to the list.sort()
method and the "key"   parameter.  See also the "Sorting HowTo" on the
PythonInfo wiki by Raymond Hettinger:

Hope is enough to get you going,


More information about the Tutor mailing list