Transcript Lists

Computer Science 111
Fundamentals of Programming I
Sequences: Lists
What Is a List?
• A list is a sequence of 0 or more data values (of any
types) called elements
E1 E2 E3
0
1
2
• The programmer can access or replace the element at
any position in a list
• An element can be inserted at any position or removed
from any position
Real-World Examples
• A shopping list
• A schedule of athletic contests
• A team roster
• An algorithm (a list of instructions)
Literals, Assignment, Comparisons,
Concatenation, for Loop
a = [1, 2, 3]
b = list(range(1, 4))
# b now refers to [1, 2, 3]
a == b
a < [2, 3, 4]
# returns True
# returns True
print(a + b)
# displays [1, 2, 3, 1, 2, 3]
print(len(a))
# displays 3
for element in [1, 2, 3]: print(element)
Similar to the behavior of strings so far
Indexing and Slicing
a = [1, 2, 3]
print(a[2])
# Displays 3
print(a[len(a) - 1])
# Displays 3
print(a[-1])
# Displays 3
print(a[0:2])
# Displays [1, 2]
Similar to the behavior of strings so far
Replacing an Element
[1, 2, 3]
1 2
3
0
2
1
To replace an element at a given position, use the subscript
operator with the appropriate index
<a list>[<an int>] = <an expression>
a = [1, 2, 3]
a[1] = 5
print(a[1])
# The list is now [1, 5, 3]
# Displays 5
Unlike strings, lists are mutable!
Replacing a Subsequence
[1, 2, 3, 4]
1 2
3
4
0
2
3
1
a = [1, 2, 3, 4]
a[0:2] = [5, 6]
print(a)
# Displays [5, 6, 3, 4]
Splitting
split builds a list of tokens (words) from a string using the
space or newline as the default separator
s = 'Python is way cool!'
lyst = s.split()
print(lyst)
# Displays ['Python', 'is', 'way', 'cool!']
<a string>.split(<optional separator string>)
Pattern Matching
lyst = ['Ken', 100]
[name, grade] = lyst
print(name)
# Displays Ken
print(grade)
# Displays 100
Application: Find the Highest Grade
fileName = input('Enter the file name: ')
inputFile = open(fileName, 'r')
highestGrade = 0
topStudent = 'Nobody'
for line in inputFile:
[name, grade] = line.split()
grade = int(grade)
if grade > highestGrade:
highestGrade = grade
topStudent = name
print(topStudent, 'has the highest grade', highestGrade)
Assumes that each line of text in the file contains two
words, a name and a grade (represented as an integer)
Joining
join builds a string from a list of tokens (words)
s = 'Python is way cool!'
lyst = s.split()
print(lyst)
# Displays ['Python', 'is', 'way', 'cool!']
print(' '.join(lyst))
# Displays Python is way cool!
<a separator string>.join(<a list of strings>)
Application: Sentence Length
Short sentences are an index of good writing style. Word
processing programs allow you to do word counts.
sentence = input('Enter a sentence: ')
words = sentence.split()
count = len(words)
print('There are', count, 'words in your sentence.')
Application: Generate Sentences
• Given a vocabulary and grammar rules, one can generate some
random and perhaps rather silly sentences
• Vocabulary - the set of words belonging to the parts of speech
(nouns, verbs, articles, prepositions)
• Grammar - the set of rules for building phrases in a sentence
(noun phrase, verb phrase, prepositional phrase)
The Structure of a Sentence
sentence
noun phrase
verb phrase
A sentence is a noun phrase followed by a verb phrase
The Structure of a Sentence
sentence
noun phrase
article
verb phrase
noun
A noun phrase is an article followed by a noun
The Structure of a Sentence
sentence
noun phrase
article
the
verb phrase
noun
girl
Similar
to the behavior of strings so far
Pick actual words for those parts of speech at random
The Structure of a Sentence
sentence
noun phrase
article
the
noun
verb phrase
verb
girl
Similar
noun phrase
prepositional phrase
to the behavior of strings so far
A verb phrase is a verb followed by a noun phrase and a
prepositional phrase
The Structure of a Sentence
sentence
noun phrase
article
the
noun
verb phrase
verb
noun phrase
girl
Similarhit
to the
prepositional phrase
behavior of strings so far
Pick a verb at random
The Structure of a Sentence
sentence
noun phrase
article
noun
verb phrase
verb
noun phrase
article
the
girl
Similarhit
to the
prepositional phrase
noun
behavior of strings so far
Expand a noun phrase again
The Structure of a Sentence
sentence
noun phrase
article
noun
verb phrase
verb
noun phrase
article
the
prepositional phrase
noun
girl
the
boy
Similarhit
to the behavior
of
strings so far
Pick an article and a noun at random
The Structure of a Sentence
sentence
noun phrase
article
noun
verb phrase
verb
noun phrase
article
the
noun
girl
the
boy
Similarhit
to the behavior
of
prepositional phrase
preposition
noun phrase
strings so far
A prepositional phrase is a preposition followed by a noun
phrase
The Structure of a Sentence
sentence
noun phrase
article
noun
verb phrase
verb
noun phrase
article
the
noun
girl
the
boy
Similarhit
to the behavior
of
Pick a preposition at random
prepositional phrase
preposition
stringswith
so far
noun phrase
The Structure of a Sentence
sentence
noun phrase
article
noun
verb phrase
verb
noun phrase
article
noun
prepositional phrase
preposition
noun phrase
article
the
girl
the
boy
Similarhit
to the behavior
of
Expand another noun phrase
stringswith
so far
noun
The Structure of a Sentence
sentence
noun phrase
article
noun
verb phrase
verb
noun phrase
article
the
noun
girl
the
boy
Similarhit
to the behavior
of
prepositional phrase
preposition
stringswith
so far
More random words from the parts of speech
noun phrase
article
noun
a
bat
Representing the Vocabulary
nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair',
'fence', 'table', 'computer', 'cake', 'field']
verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped']
prepositions = ['with', 'to', 'from', 'on', 'below',
'above', 'beside']
articles = ['a', 'the']
Use a list of words for each part of speech (lexical category)
Picking a Word at Random
nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair',
'fence', 'table', 'computer', 'cake', 'field']
verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped']
prepositions = ['with', 'to', 'from', 'on', 'below',
'above', 'beside']
articles = ['a', 'the']
import random
print(random.choice(verbs))
# Prints a randomly chosen verb
The random module includes functions to select numbers,
sequence elements, etc., at random
Grammar Rules
sentence = nounphrase verbphrase
nounphrase = article noun
verbphrase = verb nounphrase prepositionalphrase
preopositonalphrase = preposition nounphrase
A sentence is a noun phrase followed by a verb phrase
Etc., etc.
Define a Function for Each Rule
# sentence = nounphrase verbphrase
def sentence():
return nounphrase() + ' ' + verbphrase()
Each function builds and returns a string that is an instance
of the phrase
Separate phrases and words with a space
Define a Function for Each Rule
# sentence = nounphrase verbphrase
def sentence():
return nounphrase() + verbphrase()
# nounphrase = article noun
def nounphrase():
return random.choice(articles) + ' ' + random.choice(nouns)
When a part of speech is reached, select an instance at
random from the relevant list
Call sentence() to Try It Out
# sentence = nounphrase verbphrase
def sentence():
return nounphrase() + verbphrase()
# nounphrase = article noun
def nounphrase():
return random.choice(articles) + ' ' + random.choice(nouns)
…
for x in range(10): print(sentence())
# Display 10 sentences
You can also generate examples of the other phrases by
calling their functions
Just the Tip of the Iceberg
• The list is a very powerful data structure
• There are many list processing methods
• A Python method is like a function, but uses
a slightly different syntax
The append Method
lyst = [1, 2, 3]
lyst.append(4)
print(lyst)
# Displays [1, 2, 3, 4]
Adds an element to the end of the list
Syntax for calling the append method:
<a list>.append(<an element>)
# Puts the element at the end of the list
# Actually modifies the list!!!
Functions vs Methods
lyst = [1, 2, 3]
lyst.append(4)
# A method call
print(len(lyst))
# Two function calls
file = open('testfile.txt', 'r')
# A function call
wordList = file.read().split()
# Two method calls
Syntax of method calls and function calls:
<a data object>.<method name>(<arguments>)
<function name>(<arguments>)
Some List Methods
Example Call
What It Does
lyst.count(3)
Returns the number of 3s in the list
lyst.insert('dog', 2)
Inserts 'dog' at position 2, after shifting the
elements at positions 2 through N - 1 to the right
lyst.pop(0)
Removes the element at the first position and
then shifts the remaining elements to the left by
one position
lyst.remove('dog')
Removes the first instance of 'dog' in the list
lyst.reverse()
Reverses the elements
lyst.sort()
Sorts the elements in ascending order
For Wednesday
Continue reading Chapter 5
on dictionaries