Python Lists and List Manipulation

Last time we looked at strings in Python, and various ways that we can manipulate them. We discussed how strings are essentially lists of characters and how this impacts how we can manipulate them. Let's go on and look at Python lists proper, ways we can manipulate them, and their uses in making games.

We can store any type of variable in a Python list and can mix and match the types which we store. Lists keep a consistent order, unlike some other data structures.

# an array of numbers
my_array = [1,2,3,4,5]
print(my_array)
# an array of strings
my_array = ['a','b','c','d','e']
print(my_array)
my_array = [[0,1],[2,3],[4,5]]
print(my_array)
# an array with mixed types
my_array = ['a',0,[0,1,2]]
print(my_array)

Just like a string, you reference different elements of lists by index. You can also add elements to the end of a list by using the append method. To remove items from the list you can use the pop method.

Note that in Python we often don't manipulate lists by removing items, and prefer to just create new lists.

my_array = []

for i in range(10):
  my_array.append(i * 2)

for i in range(10):
  print(my_array[i])

# remove the item at index 5
my_array.pop(5)
print(my_array)

# remove rest of items
for i in range(9):
  my_array.pop()

print(my_array)

Exercise 1

  1. Write a script to turn a string into a list of single characters. e.g. "hello" => ['h','e','l','l','o']
  2. Write a script to reverse a list without using the built-in .reverse() method.
  3. Let the user input n. Calculate the fibonacci sequence up to the nth term (indexing from 0) and print the resulting array. The first and second terms of the sequence are both equal to 1. For example, inputting 7 should output [1, 1, 2, 3, 5, 8, 13]

Useful List Operations

Like most common operations, Python gives us some interesting shortcuts for working with lists.

Just like strings we can concatenate two lists by using + or += operators. Another way to do this is to use the extend method, which adds every element from another collection to the end of the list.

list_1 = [0,1,2,3]
list_2 = [4,5,6,7]
joined = list_1 + list_2
print(joined)
joined.extend(list_1)
print(joined)

We often want to convert a string to a list of strings or vice versa, which can be accomplished with the string.join(list) method or the list.split(string) methods.

array_1 = ["hello","there","fellow","kids"]
# join the words using a space
joined = " ".join(array_1)
print(joined)
to_split = "0 1 2 3 4 5"
split = to_split.split(" ")
print(split)

We often want to loop through a list to perform some operation. There are three main ways of doing this:

my_list = [1,2,3,4,5]

# just get the value
# this is the most common method
for element in my_list:
  print(element)

# just get the index
# this is helpful if we want to change the elements in the list
for index in range(len(my_list)):
  print(my_list[index])

# get both the index and the element
# makes use of tuple unpacking, which we'll cover next time
for index, element in enumerate(my_list):
  print(f"{index}: {element}")

Exercise 2

  1. Take a list of floats as a string from the user, and convert it into an array of floats.
  2. Let the user input a space-separated list of floats; return the sum, largest number, smallest number, and mean averages of that list.

Assignment

We're going to make a simple top-down game with a map. The player will be represented as an @ character, while the map will be represented as a set of . characters.

Set up the map as a 10x10 grid by using a list of lists. Each turn, you need to redraw the map, including the player.

On each turn, the player should be able to enter u, d, l, or r for Up, Down, Left, or Right. They should move 1 square in the direction they indicate. If a move would take the player off the edge of the map, then it should fail.

Extension: Let the player move multiple times in one turn by writing a string of characters like uudldl.

Extension: Add obstacles to the game, represented by the x character. The player should not be able to move through those obstacles, just like the wall of the grid.