Lesson 11
Lists
Lists in Python (also known as arrays in other programming languages) are very powerful data structure.
stores a collection of objects or values
the objects stored in a list are called elements
the elements are ordered (i.e., there is a first, second, etc. element)
the elements in a list should usually have the same type
Initialization
a = []
b = list()
student_names = ['Justyna', 'Yong', 'Tim', 'Lucas', 'Capri']
daily_covid_cases = [14, 90, 200, 598, 1184]
temperatures = [100.5, 68.1, 87.0, 66.2]
animation_states = [WAIT, WARN, ATTACK, DIE]
colors = [Color.RED, Color.GREEN, Color.BLUE]
images = ['apple.jpg', 'ninja.png', 'sword.tga', 'background.bmp']
Accessing Elements by Index
Each element in the list has an index, an integer value corresponding to the element’s position in the list.
student_names = ['Justyna', 'Yong', 'Tim', 'Lucas', 'Capri']
print(student_names)
print(student_names[0])
# print(student_names[1])
# print(student_names[2])
# print(student_names[3])
# print(student_names[4])
# print(student_names[5])
Part 1: Basic Slideshow
Exercise 1
Download and extract the zip file below for some sample images.
Create a list of three file names. For example,
images = ['1.jpg', '2.jpg', '3.jpg', ]
Set the
window.background_image = images[0]
Create three buttons (
Sprites
) that change the background image when clicked.
- Extension:
If you finish the basic slideshow early, try this for a challenge. Make a copy of your python file and create a list of captions. Change to the different captions when you change the images.
Part 3: Infinite Slideshow
If we are showing the last image in the list, what happens when we hit the next button?
Can you come up with a solution to fix the IndexError
problem?
What if we don’t know the number of elements in the list?
The len()
Function
The len()
function returns the number of elements in a list. For example,
images = ['1.jpg',
'2.jpg',
'3.jpg',
'4.jpg',
'5.jpg',
'6.jpg',
]
print(len(images)) # will print 6
Using the len()
function is much better than using an integer literal,
because if we add or remove elements from our list, our program will still work.
Exercise 3
Use the len()
function to fix the IndexError
index out of range problem.
- Extension:
Use the mod operator
%
instead of an if statement.