-2

I have a list comprehension and want to store the results in a set. But, the list is unhashable and therefore can't be stored in a set.

Is there some way to do a tuple comprehension instead?

15
  • You came to the answer at the same second you asked the question. You are really genius! Commented Aug 29, 2021 at 19:27
  • @Prophet Somehow you make it sound like that's a bad thing to do... Commented Aug 29, 2021 at 19:35
  • It's weird how the question this is supposedly a duplicate of never showed up when I was looking for an answer. Commented Aug 29, 2021 at 19:40
  • @don'ttalkjustcode I feel this like a unfair way to gain the points. But maybe I'm wrong. Commented Aug 29, 2021 at 19:43
  • 1
    @Prophet If submitting an answer along with your question were in any way frowned upon, why do you think that that functionality even exists? Check this out. Commented Aug 29, 2021 at 20:12

1 Answer 1

1

I came up with the answer in the process of asking the question, so I figured I'd post it with my answer and help the next person to search for a solution. I couldn't find anything about a tuple comprehension, but you can just cast a list to a tuple and store that in the set. Like so:

 wave = set() for srces in itertools.combinations(games, self.size): wave.add(tuple([(book, 0) for book in srces])) 
Sign up to request clarification or add additional context in comments.

15 Comments

There's no need to have the [ ]. Without them, you'll create a generator expression, which tuple() will convert to a tuple.
In this particular example, the far better solution is to annotate the books not in the combinations but already in the games. Much faster, much less memory, and less code. Btw you can't append to a set.
@sj95126 I'm curious about the efficiency. I suspect the generator way will be faster, but don't know about memory usage. Do you?
Code doesn't work: AttributeError: 'set' object has no attribute 'append'.
@juanpa.arrivillaga Found the code I was looking for, PySequence_Tuple in abstract.c. And did some tracemalloc experiments. Seems tuple(listcomp) takes up to 2.125 N memory (1.125 for listcomp, then 1 for tuple) and tuple(generator) takes up to 1.25 N memory. The extra 12.5% and 25% for overallocating. So neither list nor tuple appear to grow by allocating a new place and moving the data, I guess the OS happily extends the existing allocation...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.