[Tutor] Extending a list within a list comprehension

Victor Bouffier victor at grupocdm.com
Wed Apr 12 07:17:35 CEST 2006

On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote:
> 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 ]

Hi Kent,
I try this one and get the following error:

TypeError: list objects are unhashable

I figured it is because of the x[0] element being used as a dict key.
Can you explain further where this error comes from? Are you getting it

> but I would make two steps, one for the sort using just
>    [ (x[0], x) for x in elements ]
You are right. This is cleaner and not a big deal to do in two steps.
However for the issue at hand, it still keeps x as a two element list:

[codigo, [ cant, importe, porc]],

which I would like to have extended:

[codigo, cant, importe, porc]

It is not a big deal. That is why I finally went with the longer version
Alan suggested. Before the sort I get a two element list, the second
element being the list I finally want as output.

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

Right. After the sort I just get that second element in another list

lines = [ x[1] for x in temp ]

Thanks for your help.

> Kent
> PS to John: the original solution is using DSU, aka Schwarzian Transform
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list