-1

I know it can be done in a for loop, but using list comprehension as below looks a little odd to me because it is just a statement without any assignment or being used as part of something else.

Couple of questions: Is there a better way to do this by making the list comprehension part of the set command above, and regardless of a better way to merge set/list comprehension is it 'standard' Python practise to have lines like this?

some_list = [[1,2,3],[4,5,6],[1,2,3]]
myset = set()

[myset.add(tuple(t)) for t in some_list]

print(myset)
Neil
  • 357
  • 2
  • 10

1 Answers1

3

Juste write

myset = {tuple(t) for t in some_list}
Holt
  • 36,600
  • 7
  • 92
  • 139
  • Crikey! I've been dumb all along. I thought {} was just dictionary comprehension, I presumed there was no such thing as set comprehension. I guess this is what happens when you reuse the same brackets :) – Neil Aug 23 '22 at 09:55
  • 1
    @Neil The alternative would be `set(tuple(t) for t in some_list)`, or `set(map(tuple, some_list))`… – deceze Aug 23 '22 at 09:58
  • 1
    @Neil It's called a *generator expression* and can be used anywhere an *iterable* is expected. – deceze Aug 23 '22 at 10:02