[Tutor] Extending a list within a list comprehension

Kent Johnson kent37 at tds.net
Wed Apr 12 04:17:50 CEST 2006


Victor Bouffier wrote:

> If the second element in each array passed as x is of variable length
> (that is, it has a different element count than three, in this case),
> the program needs to extend the list instead. Without list
> comprehensions, and the added capability to utilize and sized list as a
> second element, my code ended up looking like the following:
> 
> 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 ]
> 
> Is there a way to use list comprehensions to append or extend the array
> as needed by the second code listing?

I think you are looking for
temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ]

but I would make two steps, one for the sort using just
   [ (x[0], x) for x in elements ]

then when you pick the data back out you can format it how you like.

Kent

PS to John: the original solution is using DSU, aka Schwarzian Transform



More information about the Tutor mailing list