Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting first n elements of a set [duplicate]

Tags:

python

i have a large set of elements to iterate over. for debugging purposes, i'd only like to iterate over the first, say, ~10. To achieve this, i've created a list initialised from my set, selected the first 10 elements via [:10], and iterated over the resulting list. Is there a more pythonic way of doing this?

mySet = set(df.SomeUniqueId)
myList = list(mySet)[:10]
for i, val in enumerate(myList):
    ...
like image 804
user95308 Avatar asked Sep 13 '17 00:09

user95308


2 Answers

I'd use itertools.islice(). Generating that whole list, just to access the first few items, seems wasteful to me.

for i, val in enumerate(itertools.islice(mySet, 10)):

EDIT:

If you want to randomly choose (in contrast to arbitrarily choose) your ten elements, try random.sample().

for i, val in enumerate(random.sample(mySet, 10)):
like image 194
Robᵩ Avatar answered Oct 21 '22 16:10

Robᵩ


There are many ways to do this. Using list(set(a)) will create a list, which can take a long time depending on your set. But, since you only need to iterate for a small number of loops, I would use an iterator and a counter:

count = 0
for elem in iter(mySet):
    count = count + 1
    if count == 10:
        break
    print elem

This would avoid the overhead of creating a long list, and the overhead of having some manual code to control the loop is likely to be negligible.

like image 26
Tiago1984 Avatar answered Oct 21 '22 16:10

Tiago1984