[Tutor] Extending a list within a list comprehension

Alan Gauld alan.gauld at freenet.co.uk
Wed Apr 12 00:42:29 CEST 2006


Hi Victor,

I've gotta say that I much prefer the second version here.

> temporal = []
> temporal = [ [x[1][1], (x[0], description[x[0]],
>    x[1][0], x[1][1], x[1][2] ) ] for x in elements ]
> temporal.sort()
> temporal.reverse()          # sort descending
> elements = [ x[1] for x in temporal ]
> 
> 
> temporal = []
> for x in elements:
>    lst = [x[0], description[x[0]]]
>    lst.extend(x[1])
>    temporal.append([x[1][1], lst])
> temporal.sort()
> temporal.reverse()          # sort descending
> elements = [ x[1] for x in temporal ]
> 

That looks a lot easier to rtead (and debug) and will I suspect be 
easier to maintain. Copmprehensions are great but unfortunately 
can rapidly become incomprehensible!

> Is there a way to use list comprehensions to append or extend the array
> as needed by the second code listing?

There may be but I wouldn't try.
I might however look at using a simple list or dictionary of objects based 
on a class... It might be easier.

Alan G



More information about the Tutor mailing list