donut donut - 9 days ago 7
Python Question

Difference in two methods for calling a function for a group of sprites

In Pygame, I have come across two different ways to call a function for all of the sprites in a sprite group:

1)

example_group.update()


2)
for sprite_loop in example_group: sprite_loop.update()


Unless I am mistaken, they both accomplish the same thing.

Is there a significant difference between the two methods? Is one better for performance? I would think that the first method would be faster, but most of the example code I have read used the second method.

Here is some code to put it in context:

import pygame
class Test(pygame.sprite.Sprite):
def __init__(self):
super(Test, self).__init__()
self.x = 0
example_group.add(self)

def update(self):
self.x += 1
if self.x == 1:
print self.x

example_group = pygame.sprite.Group()

sprite1 = Test()
sprite2 = Test()
sprite3 = Test()

while True:

#THIS IS WHERE MY QUESTION IS

#DO I USE:
example_group.update()

#OR SHOULD I USE:
for sprite_loop in example_group:
sprite_loop.update()

Answer

They do acheive the same. The group update function calls the Sprite update. Both should be equivalently performant. Whichever you call is your preferrence.

You can compare the documentation for them

Sprite.update

Group.update

You would use the for loop if you didn't want to update all the sprites under certain conditions