[Tutor] Extending a list within a list comprehension
Kent Johnson
kent37 at tds.net
Wed Apr 12 12:08:12 CEST 2006
Victor Bouffier wrote:
> 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
It's helpful if you show the traceback as well as the error message.
>
> 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
> too?
No, I don't know what is causing it. Isn't x[0] a string? What is
description? I didn't run the code myself.
Kent
More information about the Tutor
mailing list