Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Matthew Allcorn
4,339 PointsGetting "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
216,812 PointsIn 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
4,339 PointsMatthew Allcorn
4,339 PointsThanks 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}')