# shuffle a sprite group

Is there a way to shufle a group of sprites created with:

pygame.sprite.Group()


I have tried using random.shuffle but it apparently doesn't work on sprite groups.

Since groups are an iterator, you can use:

sprs = list(spr_group)
random.shuffle(sprs)


You should not rely on Python's hashing order to randomize sprites for you. It is not a good RNG.

According to pygame documentation:

The Sprites in the Group are not ordered, so drawing and iterating the Sprites is in no particular order. http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group

I think the best you can do is not to use the Group, and make your own group mechanism. If you need only ordered update then use http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.OrderedUpdates

• Thanks, I will keep the sprite group though. Your first sentence is correct, each time I create/empty/create the group it comes back in a different order, which is just what I need.
– user3956
May 2 '11 at 9:31
• -1. If you desperately need the group to shuffle you can simply subclass Group, you don't need to avoid it. But you probably don't want the group per se to be shuffled; you just want a shuffled copy of the sprites in the group.
– user744
May 2 '11 at 13:34

As other already said, the sprite.Group iterator yield its members in an unordered way (like a dict, not like a a list).

So if you're after a simple unordered list (not properly shuffled with a random method - if you want that follow user744's answer), just get what it gives by default.

The "problem" here is quite the contrary: how to get an ordered list of sprites from it (or a sprite by its index in the group)