[Tutor] New to list & first steps in Python

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jun 3 14:57:59 EDT 2004



On Thu, 3 Jun 2004, Chris F Waigl wrote:



> from random import *  # or "... import choice" ?
> adj1 = []
> adj2 = []
> nouns = []
> file = open("ElisabethInsults", "r")
> for line in file.readlines():
>     words = line.split()
>     adj1.append(words[0])
>     adj2.append(words[1])
>     nouns.append(words[2])
> print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!"
> file.close()


Hi Chris,

This looks fine.  You may want to avoid using the 'from foo import *'
statement.  I agree that explicitely pulling out the 'choice' function is
better:

###
from random import choice
###


There's a section on the official Python tutorial that talks about the
reasons why it's a good idea to avoid it:

    http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000



One other improvement is to use direct iteration across file objects: we
can avoid calling the readlines() method.

> file = open("ElisabethInsults", "r")
> for line in file.readlines():
>     words = line.split()
>     adj1.append(words[0])
>     adj2.append(words[1])
>     nouns.append(words[2])


Python supports iteration directly across file objects, so this can be
simplified to:

###
file = open("ElisabethInsults", "r")
for line in file:
    words = line.split()
    adj1.append(words[0])
    adj2.append(words[1])
    nouns.append(words[2])
###

That is, the file looks almost like a 'sequence' of lines.  In Python
terminology, it's an 'iterable', which means that the for loop works on it
directly.  By avoiding readlines(), we dodge loading the whole
ElisabethInsults file into memory at once.  There are a few things in
Python that are iterables, including strings, files, and lists.



> ElisabethInsults is a file containing three rows, 2 x adjectives, 1 x
> nouns, of derogatory words taken from Shakespeare. (If you're
> interested, it's here: http://kastalia.free.fr/misc/ElisabethInsults )
> The script creates a random insult, e.g. "Thou clouted onion-eyed
> pigeon-egg!"

Awesome.  Your program looks very clear; I like it.  Keep the questions
coming!  *grin*


Good luck to you!




More information about the Tutor mailing list