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
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
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.
#!/usr/bin/env python
#
# Program to read and print a file
#
file = open("alice.txt","r")
text = file.readlines()
file.close()
for line in text:
print line,
print
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.
#!/usr/bin/env python
#
# Program to read and print a file
#
file = open("alice.txt","r")
line = file.readline()
while line:
print line,
line = file.readline()
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()
text = file.readlines()
file.close()
for line in text:
print line,
print
#!/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.