#### 1) Creating Lists

 zoo = ["monkey", "tiger", "eagle"] # define a list zoo[0] # a single element zoo[0] = "gorilla" # change an element zoo.append("parrot") # add elements at end of list zoo = ["zebra","lion"] + zoo # add elements at beginning

#!/usr/bin/env python
#
# creating and modifying a list
#

zoo = ["monkey", "tiger", "eagle", "parrot"]

print "The zoo has the following", len(zoo), "animals:", zoo

print "The 1. animal is", zoo[0]
print "The 2. animal is", zoo[1]
print "The 1. and 2. animals are", zoo[:2]
print "Animals 2. - 4. are", zoo[1:4]
print "The animals after the 2. one are", zoo[2:]
print "The last element is", zoo[-1]

new_animal = raw_input("Which animal would you like to add? ")
zoo.append(new_animal)
print "The zoo has the following", len(zoo), "animals:", zoo

new_animal = raw_input("Which animal should replace the monkey? ")
zoo[0] = new_animal
print "The zoo has the following", len(zoo), "animals:", zoo

#### Exercise

1.1) Create a list that contains the names of 5 students of this class. (Do not ask for input to do that, simply create the list.) Print the list. Ask the user to input one more name and append it to the list. Print the list. Ask a user to input a number. Print the name that has that number as index. Add "John Smith" and "Mary Miller" at the beginning of the list (by using "+"). Print the list.

#### 2) More operators and functions for lists

 del zoo[0] # delete an element by index number zoo.remove("tiger") # delete an element by value zoo.insert(1, "elephant") # insert an element len(zoo) # length of zoo max(zoo) # alphabetically first or smallest element min(zoo) # alphabetically last or largest element new_zoo = zoo[:] # create a new copy of zoo zoo.reverse() # change the list to reverse order zoo.sort() # change the list to alphabetical order

#!/usr/bin/env python
#
# Deleting elements from a list

zoo = ["monkey", "tiger", "eagle", "parrot"]
print "The zoo has the following", len(zoo), "animals:", zoo

number = input("Which animal would you like to delete? \
Input the number of the animal: ")
if 0 <= number < len(zoo):
del zoo[number]
else:
print "That number is out of range!"
print "The zoo has the following", len(zoo), "animals:", zoo

new_animal = raw_input("Which animal would you like to delete? \
Input the name of the animal: ")
if new_animal in zoo:
zoo.remove(new_animal)
print new_animal, "has been deleted"
else:
print new_animal, "cannot be deleted because it is not in the zoo"
print "The zoo has the following", len(zoo), "animals:", zoo

#### Exercise

2.1) Continue with the script from 1.1): Print the list. Remove the last name from the list. Print the list. Ask a user to type a name. Check whether that name is in the list: if it is then delete it from the list. Otherwise add it at the end. Create a copy of the list in reverse order. Print the original list and the reverse list.

#### 3) For-statement with lists

#!/usr/bin/env python
#
# for statement
#
zoo = ["tiger", "elephant", "monkey"]
for animal in zoo:
print animal,
print

#### Exercises

3.1) Use the list of student names from exercise 2.1): Create a for loop that prints for each student "hello student_name, how are you?" where student_name is replaced by the name of the student.

3.2) Optional: Use the list of student names from the previous exercise. Create a for loop that asks the user for every name whether they would like to keep the name or delete it. Delete the names which the user no longer wants. Hint: you cannot go through a list using a for loop and delete elements from the same list simultaneously because in that way the for loop will not reach all elements. You can either use a second copy of the list for the loop condition or you can use a second empty list to which you append the elements that the user does not want to delete.

#### 4) Input from a file

#!/usr/bin/env python
#
# Program to read and print a file
#
file = open("alice.txt","r")
file.close()

for line in text:
print line,
print

File handling

 file = open("alice.txt","r") open for reading file = open("output.txt","w") open for writing file = open("output.txt","a") open for appending file.close() close file text = file.readlines() read all lines into a list called "text" line = file.readline() read next line into a string called "line" file.writelines(text) write list to file file.write(line) write one line to file

Exercises

4.1) Modify the program so that the lines are printed in reverse order.
4.2) Output to another file instead of the screen. First, let your script overwrite the output file, then change the script so that it appends the output to an existing file.
4.3) Modify the program so that each line is printed with a line number at the beginning.

#### 5) Optional Materials

Alternative method of reading a file. This method should be used for files that are too large to be read into a list at once.

#!/usr/bin/env python
#
# Program to read and print a file
#
file = open("alice.txt","r")

while line:
print line,
print

file.close()

Since reading files from the operating system environment is a source of errors, it is sometimes a good idea to add some code that detects and deals with errors:

#!/usr/bin/env python
#
# Program to read and print a file

import sys

try:
file = open("alice.txt","r")
except IOError:
print "Could not open file"
sys.exit()

file.close()

for line in text:
print line,
print

#### 6) Optional: Dictionaries

Dictionaries are like lists whose indices are arbitrary numbers and strings. They can also be thought of as "database tables" with two columns (a "key" and a "value" column).

#!/usr/bin/env python
#
# a dictionary

relatives ={"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother",
"Homer" : "father", "Santa" : "dog"}

for member in relatives.keys():
print member, "is a", relatives[member]

Exercise

6.1) Create a second dictionary (such as "age") and print its values as well.