'What is a pythonic way of slicing a set?
I have some list of data, for example:
some_data = [1, 2, 4, 1, 6, 23, 3, 56, 6, 2, 3, 5, 6, 32, 2, 12, 5, 3, 2]
and I want to get unique values with fixed length (I don't care which I will get) and I also want it to be a set.
I know that I can do set from some_data then make it list, crop it and then make it set again.
set(list(set(some_data))[:5]) # doesn't look so friendly
I understand that I don't have __getitem__ method in set which wouldn't make the whole slice thing possible, but if there is a chance to make it look better?
And I completely understand that set is unordered. So it doesn't matter which elements are in final set.
Possible options are to use:
using
dictwithNonevalues:set(dict(map(lambda x: (x, None), some_data)).keys()[:2]) # not that great
Solution 1:[1]
You could sample the set
import random
set(random.sample(my_set, 5))
The advantage of this you'll get different numbers each time
Solution 2:[2]
You could try a simple set comprehension:
some_data = [1, 2, 4, 1, 6, 23, 3, 56, 6, 2, 3, 5, 6, 32, 2, 12, 5, 3, 2]
n = {x for i, x in enumerate(set(some_data)) if i < 5}
print n
Output:
set([32, 1, 2, 3, 4])
Solution 3:[3]
I went through all the examples above and all of the answers are indeed great. I have one more approach to share in order to slice sets i.e. the use of the * operator. This approach requires us to use variables in order to store the memory address/references of elements. The final output we get after slicing is a list so if we want the final output to be a set we need to typecast the final result into a list or any other datatype we want to. The image of the code cannot be embedded since I do not have 10 points and therefore a link to the image of the code is given. Kindly do have a look and feel free to provide any suggestions regarding the same. Thanks.
The sample code image
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ChatterOne |
| Solution 3 | Slava Rozhnev |

