Download presentation
Presentation is loading. Please wait.
Published byAmber Clark Modified over 9 years ago
1
Computer Science 101 Python Lists
2
Literals, Assignment, Comparisons, Concatenation Similar to the behavior of strings so far a = [1, 2, 3] b = 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
3
Indexing 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
4
Replacing an Element To replace an element at a given position, use the subscript operator with the appropriate index [ ] = 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
5
Splitting split builds a list of tokens (words) from a string using the space as the default separator s = 'Python is way cool!' lyst = s.split() print lyst # Displays ['Python', 'is', 'way', 'cool!']
6
Joining join builds a string from a list of tokens (words) using the space as the default separator s = 'Python is way cool!' lyst = s.split() print lyst # Displays ['Python', 'is', 'way', 'cool!'] print ' '.join(lyst) # Displays Python is way cool!
7
Application: Sentence Length Short sentences are an index of good writing style. Word processing programs allow you to do word counts. sentence = raw_input('Enter a sentence: ') words = sentence.split() count = len(words) print 'There are', count, 'words in your sentence.'
8
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
9
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!!! Syntax for calling the append method:
10
Functions vs Methods lyst = [1, 2, 3] lyst.append(4) # A method call print len(lyst) # A function call. ( ) ( ) Syntax of method calls and function calls:
11
Some List Methods Example CallWhat It Does lyst.count(3) Returns the number of 3s in the list lyst.insert(5, 2) Inserts 5 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(5) Removes the first instance of 5 in the list lyst.reverse() Reverses the elements lyst.sort() Sorts the elements in ascending order
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.