Python Programming Project

Tower of Hanoi

  1. List Manipulation
01. Introduction
02. Recursion
03. List Manipulation
04. The Algorithm
05. Pygame
06. Pygame

Next, let us look at how to create and manipulate lists in python. Lists are a data type used to group together values and are very useful in python because they are very versatile. Lists are also useful because they can contain values of different types, although usually all the items have the same type.

Creating a list

You can assign items to a list with an expression of the form:

list_name = [item_1, item_2]

The items are placed between square brackets and are separated by commas.

A list can also be empty: empty_list = [].

Accessing a list

To access an individual item in the list, you will have to use its index. The index is the number that represents the item’s position in the list.

To access a particular item, you have to write the index directly after the list name, in between brackets, like this: list_name[index].

A very important thing to remember is that list indices always begin with 0, not 1! So to access the first item in the list you will have to write: list_name[0].To access the second item in the list you will have to use index 1: list_name[1]. Computer scientists love to start counting from zero!

numbers = [5, 6, 7, 8]

print numbers[1] + numbers[3]

The above code gives 14 (6+8).

Note: If you pass a negative index, Python adds the length of the list to the index. For example list_name[-1] can be used to access the last item in a list.

Warning: If you get an IndexError message, you index you may be trying to use may be outside the list. So make sure to double check!

Changing an element in the list

A list index can also be used to assign a value to that particular position of the list.

fruit = ["pear", "apple", "banana", "strawberry"]

fruit[2] = "orange"

This changes "banana" to "orange".

Adding to the end of a list

A list doesn't have to have a fixed length. You can add items to the end of a list any time you like!

letters = ['a', 'b', 'c']

letters.append('d')

print len(letters)

print letters

In the above example, we first create a list called letters and assign 3 values to it. To add the string ‘d’ to the end of the list, we write the name of the list followed by: .append(‘d’). Next, we print out the length of the list using the len() function (simply put the name of the list in between the brackets) – this will give us a result of 4. Finally, we print out the final list:

['a', 'b', 'c', 'd'].

Inserting items into a List

We can also insert items into a list.

fruit.insert(1, "melon")

print animals

We insert "melon" at index 1, which moves everything after that index down by 1. This will print the result:

["pear", "melon", "apple", "banana", "strawberry"]

Slicing

Sometimes, you only want to access a certain portion of a list.

letters = ['a', 'b', 'c', 'd', 'e']

slice = letters[1:3]

print slice

print letters

In the above example, we create a list with the first 5 letters of the alphabet. In the second line, we create a new list called slice and assign it to a portion of the first list. The [1:3] part of the code shows that we are starting from the index before the colon (1) and continuing up to but not including the index after the colon (3). Remember that we start counting indices from 0! Next, we print out the slice list, which is simply: ['b', 'c']. Lastly, we print out the original list ['a', 'b', 'c', 'd', 'e'], just to show that it has not changed in any way.

If your list slice includes the very first or last item in a list, the index for that item doesn't have to be included.

list[:2] # Grabs the first two items

list[3:] # Grabs the fourth through last items

Searching a List

Sometimes you need to search for an item in a list.

colours = ["red", "blue", "yellow"]

print colours.index("blue")

First, we create a list called colours with three strings.

Then, we print the first index that contains the string "blue", which will print 1.

Looping through a List

If you want to do something with every item in the list, you can use a for loop. (It is best to recap for loops if you can not remember how they are used)

for variable in my_list:

     # Do something!

A variable name follows the for keyword; it will be assigned the value of each list item in turn. Then you write in my_list to show that the list is what the loop will be working on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.

For example:

my_list = [1,3,4,7]

for number in my_list:

     print number * 2

This gives the result:

2

6

8

14

Sorting a List

If your list is a jumbled mess, you may need to sort() it.

names = ["Jane", "Tom", "Harry"]

names.sort()

for name in names:

     print name

First, we create a list called names with three strings. The strings have not been written in any specific order. To sort the list into alphabetical order, we add .sort() to the end of the list name. When we use .sort(), we are actually modifying the list rather than returning a new list. Then, we loop through the list, printing out each name on a separate line. They are printed in this order: "Harry", "Jane", "Tom".