Lecture Notes
Lists
Collection – allows us to put many values in a single variable.
Simple variables are not collections. The previous value is overwritten when changed.
- A List is made up of list ‘constants’. Lists are surrounded by square brackets [] and the constants in the list are separated by commas. ([2,4,6,8])
- A List element can be any Python object, even another list
- A List can be empty
- Lists are mutable (they can be changed)
- This is a big difference between lists and strings. Strings are NOT mutable. Strings and lists are similar when it comes to other functions such as concatenation, slicing, the pattern for indexing the elements within the list, and others.
- When len() is used on a list, it counts the number of constants that make up the list. (not the number of characters)
- Lists can be concatenated using +
- Lists can be sliced
- List is a unique type that can be checked using type() (result: <type ‘list’>)
- An empty list can be created with list(), or setting a variable to “[]”, e.g. stuff = []
- Lists can be tested for contents using in/not in
- List is an ordered sequence
List Methods
Read more about list Methods online at: http://docs.python.org/tutorial/datastructures.html
On the page there is method: list.copy(). But when I test this method, python told me: ‘list’ object has no attribute ‘copy’
And now I realized that’s a difference between python2.7 and python 3
Methods: append, count, extend, index, insert, pop, remove, reverse, sort
append() – use to add constants to the end of a list (lst.append(‘word’))
remove() – use to remove constants from a list
sort() – use to sort the list. It changes the list permanently.
List Functions
len() – find length, max() – find highest value, min() – find lowest value, sum() – add all values
average can be found with sum()/len()
Selection in a List
Look up items in a list using an index specified in square brackets. The number in the index indicates the numbered item in the list.
For example: For friends = [‘Joseph’,’Glen’,’Sally’] using “print friends [1]” will print out “Glen” (remember numbering starts with zero)
Using Strings and Lists Together
“Split” breaks a string into parts and produces a list of strings.
abc = ‘With three words’
stuff = abc.split()
print stuff
[‘With’,’three’,’words’]
* Split sees multiple spaces as one, creates one split. * Define a delimiter for split by entering a parameter (i.e. split(‘;’) to use semicolon as a delimiter)
Broken Links in iBook “Python for Informatics” Sec 8.14 Debugging?
I encountered 404 Errors in clicking these links as referenced in Paragraph 1 of Sec 8.14 Debugging:
- “docs.python.org/lib/typesseq.html”
- “docs.python.org/lib/typesseq-mutable.html”
Respectively, these substitutes for the above worked for me:
- https://docs.python.org/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
- https://docs.python.org/2.7/library/stdtypes.html#mutable-sequence-types
Additionally, one might find the links below helpful in tweaking apart and organizing in one’s head the different (and at this point, often mind-numbing) Python operations:
- 2. Built-in Functions: https://docs.python.org/2.7/library/functions.html
- 5.6.1 String Methods: https://docs.python.org/2.7/library/stdtypes.html#string-methods
*** Something to look for when reading info from a ‘docs.python.org’ web page.
-
-
- Scroll to bottom of screen and make sure the version is 2.7.x and not the latest 3.x.x.
-
Glossary
- Mutable – an object which allows an element of its contents to be changed. Lists are mutable meaning that one value can be changed without affecting the other objects in the list. (i.e. “lotto[2] = 28” changes the value of the third list item to ’28’)
- Immutable – an object which does not allow an element of its contents to be changed. Strings are immutable, meaning once the value is defined it cannot be changed. (it can be overwritten, but not changed) For example, a single letter’s case cannot be changed within the string. (i.e. “fruit[0] = ‘b'” results in an error)
- Range is a function that creates and returns a list of numbers that range from zero to one less than the parameter. (i.e. “print range(4)” returns “[0,1,2,3]”)
Del
- Del is a command which removes what corresponds to the index of the list. For example, if we have
a = [1, 2, 3, 4, 5] del a[0] returns [2, 3, 4, 5].
If we have multiple arguments after del, then del first updates the list, and then removes the next argument. For example if
a = [1, 2, 3, 4, 5] del a[0], a[2] returns [2, 3, 5], since a[0] first gets deleted yielding [2, 3, 4, 5], then since the 2-element of [2, 3, 4, 5] is 4, 4 gets deleted.
Here is another solution for Exercise 8.1 with guarding action taking place. Critique and comment, please:
def chop(mlist): # this function returns nothing if len(mlist)==0: print 'there is nothing to chop' exit() if len(mlist)==1: print 'only one element found, deleted..' del mlist[0] exit() else: print 'first and last element deleted' del mlist[0] del mlist[len(mlist)-1]
Here is another solution for Exercise 8.1
Mike R.’s comment: This alternate solution for the ‘chop’ function does not produce the requested result. The exercise specifically states to modify the original list, not a copy. That is why it says to return “None”, because the original list is being changed (and it doesn’t make sense to return a result in that situation). This solution is based on a misinterpretation of the exercise.
origList = [1, 2, 3, 4, 5, 6, 7] def chop(origList): newList = list(origList) # copy to a new list del newList[0] # remove 1st element del newList[len(newList)-1] # remove last element return newList[:] # the Question doesn't make sense. Why write a function that return None. # I changed it to return the newList[:] instead. Just comment out this line # with a "#" and it will return None. def middle(origList): newList = list(origList) return newList[1:-1] print "Original list:", origList print "Chopped list:", chop(origList) print "Only middle list:", middle(origList)
Solution to Exercise 8.2:
fhand = open('mbox-short.txt') count = 0 for line in fhand: words = line.split() # print 'Debug:', words if len(words) == 0 : continue if words[0] != 'From' : continue try: count = count + 1 print words[22] except: print 'Index out of range.' break With the result: "Index out of range."
Solution to Exercise 8.3:
fhand = open('mbox-short.txt') count = 0 for line in fhand: words = line.split() # print 'Debug:', words if len(words) == 0 or words[0] != 'From': continue try: count = count + 1 print words[24] except: print 'Index out of range.' break With the result: "Index out of range."
Here is another solution to Exercise 8.3, using the “and” logical operator, instead of “or”:
fhand = open('mbox-short.txt') count = 0 for line in fhand: words = line.split() if len(words) != 0 and words[0] == 'From' : count = count+1 print words[2], count else : continue
Solution to Exercise 8.6:
numlist = list() while True: inp = raw_input('Enter a number, when done entering numbers, type "done": ') if inp == 'done':break value = float(inp) numlist.append(value) print numlist print 'this is: ',numlist print min(numlist) print max(numlist) Result: Enter a number, when done entering numbers, type "done": 12 [12.0] Enter a number, when done entering numbers, type "done": 3 [12.0, 3.0] Enter a number, when done entering numbers, type "done": 56 [12.0, 3.0, 56.0] Enter a number, when done entering numbers, type "done": 156 [12.0, 3.0, 56.0, 156.0] Enter a number, when done entering numbers, type "done": done this is: [12.0, 3.0, 56.0, 156.0] 3.0 156.0
About Exercise 8.6
the code below is not an exact solution, but an interesting way to do the same thing:
numlist = list() while True: inp = raw_input("Enter a number: ") if inp == "done": break num = float(inp) numlist.append(num) numlist.sort() print "Maximum:",numlist[-1] print "Minimum:",numlist[0]