Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Basic Object-Oriented Python Creating a Memory Game Game Class Part 1

Matthew Allcorn
Matthew Allcorn
4,343 Points

Getting "IndexError: list index out of range"

Hi everyone - hoping someone can help me out because I have gone back and forth and for the life of me can not see what I have done wrong. If someone could help me out and let me know I will be eternally grateful.

from memory_cards import Card
import random


class Game:
    def __init__(self):
        self.size = 4
        self.card_options = ['Sasa', 'Dada', 'Muma', 'Simo', 'Nana', 'Popa', 'Pipi', 'Leee']
        self.columns = ['A', 'B', 'C', 'D']
        self.cards = []
        self.locations = []
        for column in self.columns:
            for num in range(1, self.size + 1):
                print(f'{column}, {num}' )


    def set_cards(self):
        used_locations = []
        for word in self.card_options: 
            for i in range(2):
                available_location = set(self.locations) - set(used_locations)
                random_location = random.choice(list(available_location))
                used_locations.append(random_location)
                card = Card(word, random_location)
                self.cards.append(card)

if __name__ == '__main__':
    game = Game()
    game.set_cards()
    for card in game.cards:
        print(card)

Other File

class Card:
    def __init__(self, card, location):
        self.card = card
        self.location = location
        self.matched = False

    def __eq__ (self, other):
        return self.card == other.card

    def __str__(self):
        return self.card

if __name__ == '__main__':
    card1 = Card('egg', 'A1')
    card2 = Card('egg', 'B1')
    card3 = Card('horse', 'C1')

1 Answer

Steven Parker
Steven Parker
229,657 Points

In the video, the Game class constructor populates the "locations" array, but the code shown here just prints the values instead. Since the "locations" array (self.locations) is never populated, when available_location is created it is also empty. Attempting to call random.choice on an empty list then produces that error.

Matthew Allcorn
Matthew Allcorn
4,343 Points

Thanks Steven - I realised that I had missed changing print(f'{column}, {num}' ) Used to run the test in the initial video to: self.locations.append(f'{column}, {num}')