320 likes | 413 Views
Creating Lists . To create a list, put a number of expressions in square brackets: listvar = [ ] #Empty list with nothing in it. A list with things in it: # create a list with some items listvar1 = [2,10,8,4,17 ]
E N D
Creating Lists • To create a list, put a number of expressions in square brackets: listvar = [ ] #Empty list with nothing in it. • A list with things in it: # create a list with some items listvar1 = [2,10,8,4,17] listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] First list is a list of ints Second list is a list of strings.
Lists: listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Index 0 1 2 3 4 5 listvar1 = [2, 10, 8, 4, 17] Index 0 1 2 3 4 So to use a particular item in the list: x=listvar2[3] #”bat wing” y=listvar1[1] #10 z=listvar2[0] #”spider leg” w=listvar1[5] #??? Example: def f(listpar): randnum = randrange(0,6) return(“the candy you got was “ + listpar[randnum]) print(f(listvar2))
Lists: listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Index 0 1 2 3 4 5 listvar1 = [2, 10, 8, 4, 17] Index 0 1 2 3 4 get the length of a list len(listvar2) # will give you 6, not 5! len(listvar1) #will give you 5, not 4 Example: def f(listpar): y = len(listpar) randnum = randrange(0,y) return(“the candy you got was “ + listpar[randnum]) print(f(listvar2))
Lists: listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Index 0 1 2 3 4 5 listvar1 = [2, 10, 8, 4, 17] Index 0 1 2 3 4 test for membership with in if “eye of newt" in listvar2: return(“we can do chemistry!") else: return(“Sorry, no chemistry today.”)
Lists: Index: 0 1 2 3 4 5 listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Slice: 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 listvar1 = [2, 10, 8, 4, 17] Slicing: x = listvar2[3:5] #x now holds [“bat wing”,”slug butter”] y = listvar1[1:2] #y now holds [10]
Lists:Slicing (Different from Indexing) Index: 0 1 2 3 4 5 listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Slice: 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 def f(): return(listvar[0:6]) >>[“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] def g(): return(listvar2[1:3]) >>[”toe of frog”,”eye of newt”] def h(): return(listvar2[-4:-2]) >>[”eye of newt”,”bat wing”] def i(): return(listvar2[-4:4]) >>[”eye of newt”,”bat wing”]
Shortcuts Index: 0 1 2 3 4 5 listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Slice: 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 listvar2[0:4] [“spider leg”,”toe of frog”,”eye of newt”,”bat wing”] listvar2[:4] [“spider leg”,”toe of frog”,”eye of newt”,”bat wing”] listvar2[3:6] [“bat wing”, “slug butter”,”snake dandruff”] listvar2[3:] [“bat wing”, “slug butter”,”snake dandruff”] listvar2[:] [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”]
Lists (Stuff we can do to lists) listofstuff = [“ant", “bear", “cat", “dog“,”elephant”,”fox”] # assign by index listofstuff[0] = “aardvark" print(listofstuff) >>>[“aardvark", “bear", “cat", “dog“,”elephant”,”fox”] # assign by slice listofstuff[3:5] = [“dolphin"] print(listofstuff) >>>[“aardvark ", “bear", “cat", “dolphin”,”fox”] # delete an element del listofstuff[2] print(listofstuff) >>>[“aardvark ", “bear", “dolphin”, ”fox”] # delete a slice del listofstuff[:2] print(listofstuff) >>>[ “dolphin”,”fox”]
Concatenate(join) lists list1 = [“skeletons", “zombies ", “witches"] list2 = [“vampires", “ghouls ", “werewolves"] list3 = list1 + list2 print(list3) >>>[“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves"] list1 +=list2 print(list1) >>>[“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves"] list1[3]? list1[0]? list1[6]?
Note: adding to the end of the list: list1 = [“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves"] We CAN do: list1[4] = “ghosts” print(list1) >>> [“skeletons", “zombies ", “witches“,”vampires", “ghosts ", “werewolves"] We CAN’T do: list1[6] = “poltergeists” (why not?)
Appending to end of list: list1 = [“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves"] We CAN’T do: list1[6] = “poltergeists” Instead: list1.append(“poltergeists”) print(list1) >>[“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves“,”poltergeists”] Append adds an element to the end of a list Always to the end! It is a method (function) that belongs to anything that is of the list type
List Methods • Methods are functions that manipulate lists specifically • lists are objects (object-oriented programming) • Objects have methods (functions) associated with them. • E.g., dog objects might have a walking function • Square objects might have a calc_area function • List objects have functions: e.g., • Add an element • reverse the list • Sort a list • Etc.
list1=[“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves“, ”poltergeists”] list1.remove(“werewolves”) >>[“skeletons", “zombies ", “witches“,”vampires", “ghouls ",”poltergeists”] Trying to remove something that isn’t in the list gives you an error: list1.remove(“ghosts”) #ERROR So check: if “vampires” in list1: list1.remove(“vampires”) print (list1) >>>[“skeletons", “zombies ", “witches“, “ghouls ", ”poltergeists”] remove() ONLY removes the first occurrence of an item in the list: list2 = [8,2,3,1,5,3,8,4,2,3,5] list2.remove(2) print(list2) >>[8,3,1,5,3,8,4,2,3,5] Removing an item from the list:
Reversing the order of the list: list1.reverse() print(list1) >>>['poltergeists', 'ghouls', 'witches', 'zombies', 'skeletons'] Sorting the list list1.sort() print(list1) >>>['ghouls', 'poltergeists', 'skeletons', 'witches', 'zombies'] Sorting the list list1.sort(reverse = True) print(list1) >>>['zombies', 'witches', 'skeletons', 'poltergeists', 'ghouls'] list1=[“skeletons", “zombies ", “witches“, “ghouls ", ”poltergeists”]
Other methods available for lists • count(value) – counts the number of times value occurs in list • list2 = [8,2,3,1,5,3,8,4,2,3,5,3] x = list2.count(3) print(x) >>>4 • index(value) – returns index of first occurrence of value list1=[“skeletons", “zombies ", “witches“, “ghouls ", ”poltergeists”] y = list1.index(“witches”) print(y) >>>2
pop([f]) – returns value at position f and removes value from list. Without f, it pops the last element off the list list1=[“skeletons", “zombies ", “witches“, “ghouls ", ”poltergeists”] x=list1.pop() print(x) >>”poltergeists” print (list1) >> =[“skeletons", “zombies ", “witches“, “ghouls ”] x=list1.pop(2) print(x) >>”witches” print (list1) >> [“skeletons", “zombies ", “ghouls ”] • insert(f,value)- inserts value at position f list1.insert(1,’dragons”) print(list1) >>>[“skeletons", “dragons”, “zombies ", “ghouls ”]
defrh(x,y): if y == len(x): return("Happy Halloween!") else: print(x[y]) return(rh(x,y+1)) print(rh(['witch','ghost','werewolf','vampire','toads'],0)) defrg(x,y): if len(x) == 0: return(y) else: y.append(x.pop()) return(rg(x,y)) print(rg(['witch','ghost','werewolf','vampire'],[])) defrf(y,ls): if ls.count(y) == 0: return(ls) else: if y in ls: z = ls.index(y) ls.pop(z) return(rf(y,ls)) x = ['a','c','b','a','d','b','a','c','b','f','c','b'] print(rf('c',x)) • list1.append(“poltergeists”) • list1.reverse() • list1.sort() • list1.count(“werewolves”) • y = list1.index(witches) • x=list1.pop(2) • list1.insert(1,’dragons”)
While Loop def ThreeYearOld(): response = "" while (response != "Because."): response = input("But why?") return("Oh. Okay.") print(ThreeYearOld()) • Look at this code: • What is our starting condition? • What must be true in order for the loop to start? • Has everything been initialized BEFORE THE loop that is needed for the loop to start? • What will make the loop end? • What must become false? • Does something INSIDE the loop that changes so that eventually the loop will end?
Loops: • def f(x): • counter = 0 • while counter < x: • print(counter) • counter = counter + 1 • return(counter) • print(f(5)) • Look at this code: • What is our starting condition? • Has everything been initialized that is needed for the loop? • What will make the loop end? • What must become false? • Is there something INSIDE the loop that changes so that eventually the loop will end? • What does this code print out?
While loops def f(): count = int(input("Enter a number")) total = 0 while count >= 1: total += count count = count -1 return(total) print(f()) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?
While loops def f(): total = 0 while count >= 1: total += count count = count -1 return(total) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?
While loops def f(): total = 0 count = 4 while count >= 1: total += count return(total) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?
Write a function that takes as an input parameter an integer and prints out "ha" that number of times. • Starting condition? • What makes the loop stop? (your True/False condition?) • What inside the loop changes so that the loop will stop? • Or • def func(x): • stringvar = "" • while (x > 0): • stringvar += "ha ") • x -= 1 • return(stringvar) • print(func(5)) • def func(x): • while (x > 0): • print("ha ") • x -= 1 • return • func(5)
Write a function that takes as an input parameter a list. The function then goes through the list and adds up every number in the list. def w1(ls): y = 0 total = 0 while y < len(ls): total += ls[y] y += 1 return(total) print(w1([3,2,4,5,1,7,3]))
What does this do? def w2(x,y): tot = 0 while (y > 0): tot += x y -= 1 return(tot) print(w2(3,5))
What about this? def w3(ls): x = ls[0] i = 0 y = 1 while y < len(ls): if ls[y] > x: x = ls[y] i = y y += 1 return("It is " + str(x) + " at " + str(i)) print(w3([3,2,4,5,1,7,3]))
How about this one? def w4(x, y, z): if (y >= 0) and (y <= x): g = -1 while (g != y): g = randrange(0,x) z.append(g) print(z) return("It took " + str(len(z)) + " tries") print(w4(35,12,[]))
What about this one? def w5(x,y): z = y.count(x) while z > 0: y.pop(y.index(x)) z = y.count(x) return(y) print(w5(3,[2,3,4,5,3,2,5,1,3,2,3,1,3]))
Versus: def z(ct): x = 0 while (ct >= 0): ct = ct - 1 x += ct return(x) print(z(5)) def z(ct): x = 0 while (ct >= 0): x += ct ct = ct - 1 return(x) print(z(5))
What do we get? Rules: • The contents of the while loop is only what is indented under the while loop • We do the contents of the while loop over and over until the while loop’s condition becomes false. • Only then do we do what is below the while loop. def q(x,y): ct = 0 while (ct < x): ct2 = 0 while (ct2 < y): print(ct + ct2) ct2 += 1 ct += 1 return q(4,3)
What does this print out? def h(x): ct = 1 while (ct <= x): ct2 = ct while (ct2<=x): print(ct2, end=" ") ct2 += 1 ct += 1 print("\n") #this is a line break (starts a new line) print("\n") #this is a line break (starts a new line) return h(5)
Can you reverse it Output: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Output: 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5 def h(x): ct = 1 while (ct <= x): ct2 = ct while (ct2<=x): print(ct2, end=" ") ct2 += 1 ct += 1 print("\n") print("\n") return h(5) def h(x): ct = 1 while (ct <= x): ct2 = 1 while (ct2<=ct): print(ct2, end=" ") ct2 += 1 ct += 1 print("\n") print("\n") h(5)