# List operations

Slicing is one way of locating certain items in a list. For example, myList[1:3] will print item 1 and item 2 (remember lists start at item 0). len() can be used to find the length of a list.

 1 2 3 4 5 my_list = [5,7,12,9,4,6,8,9] length = len(my_list) print(length) my_list.reverse() #can be used to reverse the list 

## Adding and taking away from a list of items

Here are some useful functions:

• my_list.append(“lion”) - will add the item lion to the end of the list
• my_list.insert(3,”lion”) - will add “Lion” before item 3 in the list
• my_list.pop(5) - will delete the 5th item

This video clip shows how to add and delete items from a list

## Exercise - A FOR loop and a list

What do you think this function will do? Type in the code and see if it did what you thought it would.

 1 2 3 4 def mystery(): animals =["dog","cat","fox","rabbit","deer","pig"] for counter in range(len(animals)): print("Animal {0} is {1}".format(counter,animals[counter])) 

Now make some improvements to the code.

by Sue Sentance.
20 June 2011.
updated on 03 September 2014.

Find the solutions to these exercises on GitHub.