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):
...
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)):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With