-6

I wanted to choose an image from a list of other images at random and blit them. This is an example of what i have so far.

Q1 = pygame.image.load("Math/Q1.jpg").convert()
math_list.append(Q1)
Q2 = pygame.image.load("Math/Q2.jpg").convert()
math_list.append(Q2)
Q3 = pygame.image.load("Math/Q3.jpg").convert()
math_list.append(Q3)
Q4 = pygame.image.load("Math/Q4.jpg").convert()
math_list.append(Q4)
Q5 = pygame.image.load("Math/Q5.jpg").convert()
math_list.append(Q5)

These are the variables i have appended to the list math_list. How would i now randomly choose one image, blit it at the coordinates (200, 0) and then make sure i dont open that image up again. This is not the same as any others because it does not focus on pictures exactly. And does not show how to remove after iterating over them Any help is very much appreciated. Thanks :)

user3456
  • 83
  • 1
  • 8

1 Answers1

3

You must first import random. To choose your image, do image = math_list.pop(random.randint(0,len(math_list)-1)). randint is used to choose a random number from 0 to 4, each one corresponding to an item in the list. pop removes that item and returns it to image.

Luke B
  • 2,075
  • 2
  • 18
  • 26
  • When doing that i get the following error `image = math_list.pop(random.randint(0,4)) IndexError: pop index out of range` @pydude – user3456 Oct 24 '15 at 17:11
  • @AhsenRauf see my edit. – Luke B Oct 24 '15 at 17:35
  • the code iterates and blits every single image in the list unitl it is finished and then gives an error. – user3456 Oct 24 '15 at 18:11
  • @AhsenRauf use `if len(math_list)>1: ` right before the random image chooser, and indent that line. – Luke B Oct 24 '15 at 18:12
  • It fixes the error problem but i only want a single image to show up at a time. At the moment it blits every single image continuosly until it is done @pydude – user3456 Oct 24 '15 at 18:22
  • 1
    @AhsenRauf i have solved your problem. If you want them one at a time you should post another question. Accept my answer (check mark under voting arrows) if it has helped you with your problem. – Luke B Oct 24 '15 at 18:25
  • Alright dude. Your help is greatly appreciated :) @pydude – user3456 Oct 24 '15 at 18:38
  • @AhsenRauf: you get an error when the list is empty. That is entirely consistent with your request ".. then make sure i dont open that image up again". – Jongware Nov 01 '15 at 17:00