embert
embert

Reputation: 7612

How can I write a list comprehension to create a list of sets?

I tried to create a list of sets [set([0]), set([1]), set([2]),..] using

>>> [set(i) for i in range(9)]

but it did not come out well

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not iterable

How to create that list with a list comprehension? Is it possible?

Upvotes: 1

Views: 711

Answers (1)

Inbar Rose
Inbar Rose

Reputation: 43517

To create [set([0]), set([1]), set([2]),..] with a list comprehension you would use:

>>> [{i} for i in range(5)] 
[set([0]), set([1]), set([2]), set([3]), set([4])]

Unless you are using any version of Python prior to version 2.7, then use:

>>> [set((i,)) for i in range(5)]
[set([0]), set([1]), set([2]), set([3]), set([4])]

However, it seems kind of silly that you are creating a list of sets where each set is a single integer of increasing sequence. Whatever you are trying to accomplish might be better done a different way, please consult The XY Problem and make sure you are not falling into this.

Depending on what you are trying to accomplish, there may be a better way to store your data, or perform the logic you are trying to perform.

NOTE:

Originally I wrote [set([i]) for i in range(5)] But after timing the different options, I realized that converting the integer into a single-item list is more wasteful than converting it to a tuple, so I changed my answer, and subsequently changed it again to use the set literal , timing below:

>python -mtimeit "[{i} for i in range(5)]"
1000000 loops, best of 3: 0.853 usec per loop

>python -mtimeit "[set((i,)) for i in range(5)]"
1000000 loops, best of 3: 1.64 usec per loop

>python -mtimeit "[set([i]) for i in range(5)]"
1000000 loops, best of 3: 1.87 usec per loop

Upvotes: 5

Related Questions