computer science 111 fundamentals of programming i sequences: lists
TRANSCRIPT
What Is a List?
• A list is a sequence of 0 or more data values (of any types) called elements
• 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
E1 E2 E3
0 1 2
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
Similar to the behavior of strings so far
a = [1, 2, 3]
b = list(range(1, 4)) # b now refers to [1, 2, 3]
a == b # returns Truea < [2, 3, 4] # 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)
Indexing and Slicing
Similar to the behavior of strings so far
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]
Replacing an Element
To replace an element at a given position, use the subscript operator with the appropriate index
Unlike strings, lists are mutable!
<a list>[<an int>] = <an expression>
a = [1, 2, 3]
a[1] = 5 # The list is now [1, 5, 3]
print(a[1]) # Displays 5
1 2 3[1, 2, 3]0 1 2
Replacing a Subsequence
a = [1, 2, 3, 4]
a[0:2] = [5, 6]
print(a) # Displays [5, 6, 3, 4]
1 2 3[1, 2, 3, 4]0 1 2 3
4
Splittingsplit 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 Matchinglyst = ['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 = 0topStudent = 'Nobody'for line in inputFile: [name, grade] = line.split() grade = int(grade) if grade > highestGrade: highestGrade = grade topStudent = nameprint(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)
Joiningjoin 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 LengthShort 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 verb phrase
article noun
A noun phrase is an article followed by a noun
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun
the girl
Pick actual words for those parts of speech at random
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
the girl
A verb phrase is a verb followed by a noun phrase and a prepositional phrase
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
the girl hit
Pick a verb at random
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
article noun
the girl hit
Expand a noun phrase again
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
article noun
the girl hit the boy
Pick an article and a noun at random
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
article noun preposition noun phrase
the girl hit the boy
A prepositional phrase is a preposition followed by a noun phrase
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
article noun preposition noun phrase
the girl hit the boy with
Pick a preposition at random
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
article noun preposition noun phrase
article noun
the girl hit the boy with
Expand another noun phrase
The Structure of a Sentence
Similar to the behavior of strings so far
sentence
noun phrase verb phrase
article noun verb noun phrase prepositional phrase
article noun preposition noun phrase
article noun
the girl hit the boy with a bat
More random words from the parts of speech
Representing the Vocabularynouns = ['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 Randomnouns = ['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 Rulessentence = 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 verbphrasedef 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 verbphrasedef sentence(): return nounphrase() + verbphrase()
# nounphrase = article noundef 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 verbphrasedef sentence(): return nounphrase() + verbphrase()
# nounphrase = article noundef 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]
<a list>.append(<an element>) # Puts the element at the end of the list # Actually modifies the list!!!
Adds an element to the end of the list
Syntax for calling the append method:
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
<a data object>.<method name>(<arguments>)
<function name>(<arguments>)
Syntax of method calls and function calls:
Some List MethodsExample 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