Download presentation
Presentation is loading. Please wait.
Published byLucas Bradley Modified over 9 years ago
1
Computer Science 111 Fundamentals of Programming I Sequences: Lists
2
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 E1E2E3 0 1 2
3
Real-World Examples A shopping list A schedule of athletic contests A team roster An algorithm (a list of instructions)
4
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 True a < [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)
5
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]
6
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 = [1, 2, 3] a[1] = 5 # The list is now [1, 5, 3] print(a[1]) # Displays 5 123 [1, 2, 3] 0 1 2
7
Replacing a Subsequence a = [1, 2, 3, 4] a[0:2] = [5, 6] print(a) # Displays [5, 6, 3, 4] 123 [1, 2, 3, 4] 0 1 2 3 4
8
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!'].split( )
9
Pattern Matching lyst = ['Ken', 100] [name, grade] = lyst print(name) # Displays Ken print(grade) # Displays 100
10
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)
11
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!.join( )
12
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.')
13
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)
14
The Structure of a Sentence sentence noun phrase verb phrase A sentence is a noun phrase followed by a verb phrase
15
The Structure of a Sentence sentence noun phrase verb phrase article noun A noun phrase is an article followed by a noun
16
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
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
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
25
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)
26
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
27
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.
28
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
29
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
30
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
31
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
32
The append Method lyst = [1, 2, 3] lyst.append(4) print(lyst) # Displays [1, 2, 3, 4].append( ) # 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:
33
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:
34
Some List Methods Example CallWhat 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
35
For Wednesday Continue reading Chapter 5 on dictionaries
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.