Presentation is loading. Please wait.

Presentation is loading. Please wait.

LISTS: A NEW TYPE! We've got: ints floats booleans strings and now… (drum roll) LISTS! sets of a thing (e.g., sets of ints)

Similar presentations


Presentation on theme: "LISTS: A NEW TYPE! We've got: ints floats booleans strings and now… (drum roll) LISTS! sets of a thing (e.g., sets of ints)"— Presentation transcript:

1 LISTS: A NEW TYPE! We've got: ints floats booleans strings and now… (drum roll) LISTS! sets of a thing (e.g., sets of ints)

2 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.

3 LISTS Overview The list type is a container that holds a number of objects, in a given order. Lists have an order to them Like a string, in which the order of the characters matters Examples of lists: Sound files: a long list of numbers measuring vibrations in the air any vibrational measurements The order of the measurements of vibration is dependent on when they occurred in time. List of class participants Measurements of movements (e.g., weather)

4 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”

5 LISTS: Like strings, we can use: len in listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] listvar1 = [2, 10, 8, 4, 17] get the length of a list len(listvar2) # will give you 6 if “eye of newt" in listvar2: return(“we can do chemistry!") else: return(“Sorry, no chemistry today.”)

6 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]

7 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”]

8 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”]

9 STUFF WE CAN DO TO LISTS THAT WE CAN’T DO WITH STRINGS:) 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”]

10 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]?

11 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?)

12 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 (sets aside more RAM memory) Always to the end! It is a method (function) that belongs to anything that is of the list type Appending doesn’t work with strings (They’re immutable!)

13 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.

14 Removing an item from the list: 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]

15 list1=[“skeletons", “zombies ", “witches“, “ghouls ", ”poltergeists”] Reversing the order of the list: list1.reverse() >>>[‘poltergeist’,’ghouls’,’witches’,’zombies’,’skeletons’] Sorting the list list1.sort() >>>[‘ghouls’,’poltergeists’,’skeletons’,’witches’,’zombies’] Sorting the list list1.sort(reverse = True) >>>[‘zombies’,’witches’,’skeletons’,’poltergeists’,’ghouls’]

16 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

17 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 ”]

18

19 def rg(x,y): while len(x) > 0: y.append(x.pop()) return(y) print(rg(['witch','ghost','werewolf','vampire'],[]))

20 def rf(y,ls): while ls.count(y)>0: if y in ls: z = ls.index(y) ls.pop(z) return(ls) x = ['a','c','b','a','d','b','a','c','b','f','c','b'] print(rf('c',x))

21 def f(x,y): k = True while y < len(x)//2: if (x[y] != x[len(x) - y-1]): k=False y+=1 return (x[y] == x[len(x) - y-1]) and k print(f("rotator",0)) print(f("clue",0))

22 def lr2(x,y,ls): while x < len(ls): if (ls[x] > y): y=ls[x] x += 1 return(y) listarr = [3,2,7,3,1] print(lr2(0,0,listarr))

23 def g(x,y): while (len(x) > 1): i = randrange(len(x)) y+=x[i] x = x[:i]+x[i+1:] return(y+x) print(g("computer","")) #A game comes to mind…

24 def f(x,y,z): while x < len(z): if y> z[x]: y=z[x] x+=1 return(y) print(f(0,"zzyrgy",['ghoul','zombie','werewolf','vampire','ghost','pumpkin'])) def g(x,z): while x < len(z): q = f(0,"zzyrgy",z[x:]) i = z.index(q) t = z[x] z[x] = z[i] z[i] = t x+=1 return(z) print(g(0,['ghoul','zombie','werewolf','vampire','ghost','pumpkin']))

25 def h(x): y = "" k = 0 while k<len(x): y+=(x[k][k]) k+= 1 return(y) ls = ['coffin','creepy','hayride','corpse','ghastly'] print(h(ls))

26 FOR LOOP: OUR LAST LOOP TYPE We use For loops when we know exactly how many times the loop will occur A subset of the the other two loops Form: for variable in [value1, value2,value3…lastvalue]: calculations Example: def f(): for x in [1,2,3,4,5]: print(x) return(x) print(f())

27 MORE FOR LOOPS: def f(): for x in [1,3,5,7,9]: print(x) return(x) print(f()) def f(): for x in [2,7,1,9,4]: print(x) return(x) print(f())

28 MORE FOR LOOPS: def f(): y = 0 ct = 0 for x in [3.2, 7.1, 8.0, 3.4, 5.1]: print("including " + str(x)) ct +=1 y = y + x return(y/ct) print(f())

29 LOOPS WITH STRINGS: def f(y): ct = 0 for x in ["puppy","bunny","puppy","bird","echidna","puppy"]: if x == y: ct += 1 return(ct) print(f("puppy"))

30 MORE FOR LOOPS: def f(): for x in [0,1,2,3,4]: print(x) return(x) print(f()) Shortcut: using range def f(): for x in range(5): # range(5) = [0,1,2,3,4] print(x) return(x) print(f())

31 SAME? def forfunc(y): total = 0 for x in range(y): total += x return(total) print(forfunc(5)) def whilefunc(y): count = 0 total = 0 while (count < y): total += count count += 1 return (total) print(whilefunc(5))

32 MORE ON RANGE: def f(): for x in range(-3,3): # from -3 up to but not including 3, e.g., [-3,-2,-1,0,1,2] print(x) return(x) print(f()) def f(): for x in range(-3,3,2): # from -3 up to but not including 3, by increments of 2, e.g., [-3,-1,1] print(x) return(x) print(f()) (Can we make a loop go backwards?)

33 WHAT DOES THIS DO? def f(ls): y = 1000 total = 0 for x in ls: total = total + int(x) * int(y) y /=10 return(total) print(f(["2","7","1","9"]))

34 WHAT DOES THIS DO? def f(v): var1 = "" for x in range(len(v) - 1,-1,-2): var1 += v[x] return(var1) print(f("kebijrtese"))


Download ppt "LISTS: A NEW TYPE! We've got: ints floats booleans strings and now… (drum roll) LISTS! sets of a thing (e.g., sets of ints)"

Similar presentations


Ads by Google