Arrays--part 3.
To create an array:
words = ["horse", "dog", "cow"]
creates a list with 3 elements--you can reference these elements singly
as words[0], words[1],
and words[2].
so, for example:
for i in range(3):
print words[i]
would print out the words in this list. If you want to add a 4th
word, "heffalump", you can do
words.append("heffalump")
and heffalump becomes words[3], so there are now 4 words in the
list.
-------------------------------------
A more flexible way of having a list in your program is to create on in
your Python IDLE GUI:
horse
dog
pig
heffalump
woozle
etc one word per line--call this, say, mywords.txt (it's
NOT a Python program, but a data set).
Then to read in the words:
words =
[]
this creates an initial empty list
numwds =
0
we'll keep track of how
many words there are
file = open('mywords.txt')
this opens the data file for reading
for line in
file:
a variation on a for loop
words.append(line)
adds the word to the list
numwds = numwds + 1
keeps track of how many words we have so far
We can then do
for j in range(numwds):
print
words[j]
to print out all the words
------------------------------------------
If you want to write the words to another file:
outfile =
open('copy.txt','w')
opens the file for writing
for j in range(numwds):
outfile.write(words[j])
outfile.close()
closes the file
---------------
what also works for input is
file = open('mywords.txt','r')
for line in file.readlines():
words.append(line)
numwds = numwds + 1
there are also other variations