PYTHON LISTS INTRODUCTION TO LISTS A list is

  • Slides: 17
Download presentation
PYTHON LISTS

PYTHON LISTS

INTRODUCTION TO LISTS A list is a sequence of values (called elements) that can

INTRODUCTION TO LISTS A list is a sequence of values (called elements) that can be any type. Here are some examples of lists [2, 4, 6, 8, 10] [‘a’, ’b’, ’c’, ’d’, ’e’] [‘bob’, 23. 0, 145, [1, 2]] [‘hello’, ’there’, ’Bob’] # This contains a string, float, int and # another string. Each is an element # We can put these in variables nums = [3, 2, 5, 4. 5, 3. 0, 1000] names = [‘Bob’, ’Sally’, ’Tom’, ’Harry] empty = [] print names #This is the empty string Check this out >>> ['Bob', 'Sally', 'Tom', 'Harry'] >>>

LISTS ARE ORDERED AND MUTABLE #Unlike strings we can modify the individual elements of

LISTS ARE ORDERED AND MUTABLE #Unlike strings we can modify the individual elements of a list. numbers =[7, -2, 3, 4, 5, 6. 0] #list indices work like string #indices numbers[3]=10 print numbers # we can print them [7, -2, 3, 10, 5, 6. 0] #The in operator works here as well >>>3 in numbers True

TRAVERSING A LIST for val in numbers: print val, 7 -2 3 10 5

TRAVERSING A LIST for val in numbers: print val, 7 -2 3 10 5 6. 0 # Square each number in list for I in range(len(numbers)): numbers[i]=numbers[i]**2 print numbers [49, 4, 9, 100, 25, 36. 0] The length of the following list is 4. s = [[1, 2], 3. 0, ’Harry’, [3, 5, 6, 1, 2]] Of course the length of s[3] is 5 The length of [] is 0

OPERATIONS ON LIST + works like it does on strings, i. e. it concatinates

OPERATIONS ON LIST + works like it does on strings, i. e. it concatinates [1, 2, 3]+ [4, 5, 6] becomes [1, 2, 3, 4, 5, 6] and [1, 2, 3]*3 becomes [1, 2, 3, 1, 2, 3] What does 10*[0] give you? [0, 0, 0, 0]

LIST SLICES t = [11, 21, 13, 44, 56, 68] print t[2, 4] [13,

LIST SLICES t = [11, 21, 13, 44, 56, 68] print t[2, 4] [13, 44] # Remember: It doesn’t include slot 4!! print t[3: ] [44, 56, 68] # check this out t[2: 5]=[7, 3, 1] # You can update multiple elements print t [11, 21, 7, 3, 1, 68]

LIST METHODS # Append : adds a new element # to the end t=[2,

LIST METHODS # Append : adds a new element # to the end t=[2, 4, 6] t. append(8) print t [2, 4, 6, 8] #extend: adds a list to end of list t=[‘a’, b’, c’, d’] t. extend([‘w’, ’x’]) print t [‘a’, b’, c’, d’, ’w’, ’x’] #Sort: sorts the list in place t = [4, 3, 5, 2, 7, 1] t. sort() print t #t is modified! [1, 2, 3, 4, 5, 7]

ACCUMULATING A LIST def add_them(t): # here t is a list of numbers total

ACCUMULATING A LIST def add_them(t): # here t is a list of numbers total =0 for x in t: total += x # same as total = total + x return total # Python already has something like this built in, called sum total = sum(t) #would return its sum # of course you could write your own function to do anything #you want to the elements of t

RETURNING A LIST #What does the following do? def do_it (s): # Here s

RETURNING A LIST #What does the following do? def do_it (s): # Here s is a list of strings res =[] for a in s: res. append(s. capitalize()) return res These guys traverse a list and return parts of it in another list #Returns a list of positive #numbers def get_pos(t): res = [] for i in t: if i>0: res. append(i) return res

DELETING FROM LIST t=[6, 3, 7, 8, 1, 9] x=t. pop(3) #remove element in

DELETING FROM LIST t=[6, 3, 7, 8, 1, 9] x=t. pop(3) #remove element in slot 3 and assign it to x print t [6, 3, 7, 1, 9] #note : element in slot 3 ie 8 is now gone --------------------------------------------del t[3] #does the same thing as pop(3) but returns nothing --------------------------------------------t. remove(8) #use this to remove an 8 from the list # it returns nothing

MATPLOTLIB matplotlib. pyplot is a collection of command style functions that make matplotlib work

MATPLOTLIB matplotlib. pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: eg, create a figure, create a plotting area in a figure, plot some lines in a plotting area, decorate the plot with labels, etc. . import matplotlib. pyplot as plt. plot([1, 2, 3, 4]) plt. ylabel('some numbers') plt. show() from matplotlib. pyplot import * plot([1, 2, 3, 4]) ylabel('some numbers') show() Auto generates x values here!

PLOT plot() is a versatile command, and will take an arbitrary number of arguments.

PLOT plot() is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command: plt. plot([1, 2, 3, 4], [1, 4, 9, 16]) For every x, y pair of arguments, there is an optional third argument which is the format string that indicates the color and line type of the plot. import matplotlib. pyplot as plt. plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt. axis([0, 6, 0, 20]) plt. show() red circle

LINE AND TEXT PROPERTIES import matplotlib. pyplot as plt. plot([1, 2, 3, 4], [1,

LINE AND TEXT PROPERTIES import matplotlib. pyplot as plt. plot([1, 2, 3, 4], [1, 4, 9, 16], linewidth=8. 0 ) #thick line plt. axis([0, 6, 0, 20]) #sets y axis values plt. xlabel('This is the x axis', fontsize=14, color = 'red') plt. ylabel('This is the y axis') plt. title('Our Example Graph') plt. show() Text Properties 2 d Line Properties

TWO GRAPHS import matplotlib. pyplot as plt # plot graphs plt. plot([1, 2, 3,

TWO GRAPHS import matplotlib. pyplot as plt # plot graphs plt. plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], linewidth = 4. 0 , color='blue') #thick line plt. plot([1, 2, 3, 4, 5], linewidth = 4. 0, color='red') plt. axis([0, 6, 0, 30]) #sets y axis values plt. xlabel('This is the x axis', fontsize = 14, color = 'green') plt. ylabel('This is the y axis', fontsize = 14, color = 'green') plt. title('Our Example with two Graphs', fontsize = 18, color = 'blue') plt. show()

PROCESSING A LIST AND GRAPHING USING MATPLOTLIB import matplotlib. pyplot as plt #Note x

PROCESSING A LIST AND GRAPHING USING MATPLOTLIB import matplotlib. pyplot as plt #Note x and y are lists x= [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] y=[] #build y from x , same size for i in x: y. append(i**2 -2*i+3) plt, plot(x, y) plt. show() Plot parameters are lists! More points?

CSV FILES Comma separated value files are very popular and it turns out that

CSV FILES Comma separated value files are very popular and it turns out that python can easily process these guys. These are quite simple involving nothing more than data separated by commas. Normally each line of a csv file has the same number of values listed. 12, 34, 54, 6, 5 5, 43, 77, 2, 33 78, 12, 8, 4, 23 and so on. We normally read each line of the file and split it up using the commas as an indication where to separate the values.

EXAMPLE Suppose the past slides data is in file data. txt. The following program

EXAMPLE Suppose the past slides data is in file data. txt. The following program will read in each line and print it out separated by spaces (just to show it works) file = open('data. txt', 'r') for line in file: nums = line. split(', ') # nums is now a list of the values for v in nums: print v, OUTPUT: 12 34 54 6 5 5 43 77 2 33 78 12 8 4 23