Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Sprite Groups

In this lesson, you’ll learn about the sprite.Group class, and add your Player and Enemy objects to them. You’ll create two different Group objects:

  1. The first Group will hold every Sprite in the game.
  2. The second Group will hold just the Enemy objects.

Here’s what that looks like in code:

82 # Create the 'player'
83 player = Player()
85 # Create groups to hold enemy sprites and all sprites
86 # - enemies is used for collision detection and position updates
87 # - all_sprites is used for rendering
88 enemies = pygame.sprite.Group()
89 all_sprites = pygame.sprite.Group()
90 all_sprites.add(player)
92 # Variable to keep the main loop running
93 running = True

When you call .kill(), the Sprite is removed from every Group to which it belongs. This removes the references to the Sprite as well, which allows Python’s garbage collector to reclaim the memory as necessary.

Now that you have an all_sprites group, you can change how objects are drawn. Instead of calling .blit() on just Player, you can iterate over everything in all_sprites:

114 # Fill the screen with black
115 screen.fill((0, 0, 0))
117 # Draw all sprites
118 for entity in all_sprites:
119     screen.blit(, entity.rect)
121 # Flip everything to the display
122 pygame.display.flip()

Now, anything put into all_sprites will be drawn with every frame, whether it’s an enemy or the player.

For more information about the sprite.Group class, check out the pygame documentation.

gwhitelum on May 9, 2020

I’m getting an error at the end of lesson “Creating Sprite Groups” error as follows:

Traceback (most recent call last):
  File "C:/Users/Garth Whitelum/PycharmProjects/python_games/", line 95, in <module>
  File "C:\Users\Garth Whitelum\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pygame\", line 142, in add
TypeError: add() argument after * must be an iterable, not Player

Python is asking for an iterable but Player is an object. and yes my player object is lowercase and the Player class is uppercase. (my IDE is PyCharm)

Since I’m stuck I’ll look at other tutorials.

Thanks for the help

Garth Whitelum

gwhitelum on May 9, 2020

Never mind. all is well. Just had to do a spell check to see if object names are spelt the same. Sorry.

Become a Member to join the conversation.