-1

I have a list with 1000 items in it but only want to call a certain range of them.

class myClass():

    def event(self):
        #do stuff


my_list = [myClass(i) for i in range(1000)]

#incorrect part:
my_list[0 - 10].event()

Meaning that I am trying to call "event" for only the first 9 objects. What would be the correct way to write this?

smac89
  • 39,374
  • 15
  • 132
  • 179
Gabe Weiner
  • 41
  • 1
  • 4

2 Answers2

6

Do this:

for obj in my_list[:9]:
    obj.event()

Note since you just want the first 9 objects to be called, you need to use indexes 0-8 i.e. 0,1,2,3,4,5,6,7,8

smac89
  • 39,374
  • 15
  • 132
  • 179
3
[x.event() for x in my_list[:9]]

or

list(map(lambda x: x.event(), my_list[:9]))

or, as @khredos suggests,

for obj in my_list[:9]:
    obj.event()

If myClass.event() does return something (and you want to keep the result), the first is the most pythonic. If, on the other hand, myClass.event() involves side effects (and you do not want to keep the result, of course), go for the the third approach.

Alicia Garcia-Raboso
  • 13,193
  • 1
  • 43
  • 48