Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists: a new type! LISTS! sets of a thing (e.g., sets of ints)

Similar presentations


Presentation on theme: "Lists: a new type! LISTS! sets of a thing (e.g., sets of ints)"— Presentation transcript:

1 Lists: a new type! LISTS! sets of a thing (e.g., sets of ints)
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] #list of ints listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”, ”snake dandruff”] #list of strings First list is a list of ints Second list is a list of strings. Class 1

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 have indices (like strings):
listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Index listvar1 = [2, 10, 8, 4, 17] Index 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: listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Slice: 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 (Like strings)
Index: listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Slice: 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])

8 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"] >>>[“aardvark", “bear", “cat", “dolphin”,”fox”] # delete an element del listofstuff[2] >>>[“aardvark", “bear", “dolphin”,”fox”] # delete a slice del listofstuff[:2] >>>[ “dolphin”,”fox”]

9 Concatenate(join) lists
list1 = [“skeletons", “zombies ", “witches"] list2 = [“vampires", “ghouls ", “werewolves"] list3 = list1 + list2 print(list3) >>>[“skeletons", “zombies ", “witches“,”vampires", “ghouls ", “werewolves"] Or list1 +=list2 print(list1) list1[3]? list1[0]? list1[6]? Classes 2 and 3

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

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

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

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

14 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’] list1.sort(reverse = True) >>>[‘zombies’,’witches’,’skeletons’,’poltergeists’,’ghouls’] Class 3

15 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

16 insert(f,value)- inserts value at position f
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) >>”witches” >> [“skeletons", “zombies ", “ghouls ”] insert(f,value)- inserts value at position f list1.insert(1,’dragons”) print(list1) >>>[“skeletons", “dragons”, “zombies ", “ghouls ”]

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

18 def ry(x,y): while (len(y)>0): x. append(y
def ry(x,y): while (len(y)>0): x.append(y.pop()) return x print(ry([],['a','n','d','i','h','c','e']))

19 def rf(y,ls): while ls. count(y)>0: if y in ls: z = ls. index(y) ls
def rf(y,ls): while ls.count(y)>0: if y in ls: z = ls.index(y) ls.pop(z) return(ls) x = ['a','m','y','a','a','t','a','h'] print(rf('a',x))

20 def f(x,y): k = True while y < len(x)//2: if (x[y]
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(“noon",0)) print(f("clue",0))

21 def rz(x,y): ind = 0 while (ind < len(y)): if (y[ind] in x): y[ind]='a' ind+=1 return y print(rz(['b','k','e','s','o'],['c','s','t','k','m','o','r','s','n']))

22 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…

23 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))

24 def incx(): x = 1 x = x + 1 return incx() print(x) # What is printed here? def decx(): x = x - 1 decx() print(x) # What is printed here? def squrx(): x = 2 x = x * x squrx()

25 Local Variables Remember the story of how functions work?
Islands that come into existence when they are “called” (made to run) When they’re done running, a volcano erupts and the function island is destroyed All parts of the island go away EXCEPT the return value That means that if a variable comes into existence within the function, it ONLY exists while the function is running. Unless that variable is returned, it ceases to exist when the function is done running

26 Another example: def incx(x): x = x + 1 return k = 2 incx(k)
print(k) #what do you think is printed?

27 To fix: Global Variables!
x = 3 def incx(): global x x = x + 1 return incx() print(x) def decx(): x = x - 1 decx() def squrx(): x = x * x squrx() To fix: Global Variables! Global variables outlast functions Back to our analogy – global variables are airplanes that fly from function to function By making a variable global, all functions can use it If one function changes it, it stays changed for other functions NOTE: You MUST state you’re using the global variable, or python will assume you want to use a local variable. If in the code -> you said: def squrx(): x = x * x return squrx() print(x) You’d get an error

28 st = "lli" def fun1(): st = "croc" st += "us" print(st) return() fun1() def fun2(): global st st = "po"+st+"wog" fun2() def fun3(): st = "umbre"+st[2:4] + "a" return fun3()

29 for y in range(len(ls)): print(ls[y],end="") print() return
ls = [] def f1(x): global ls ls.append(x) return def f2(x,y): ls.insert(x,y) def f3(): ls.pop() def f4(x): ls.remove(x) def f5(x,y): if (len(ls)>y): ls[y]=x def f6(x,y,z): if (y < z): if z<= len(ls): ls[y:z]=x elif (z < y): if y <= len(ls): ls[z:y]=x def f7(): global ls for y in range(len(ls)): print(ls[y],end="") print() return def main(): f1('s') f1('b') f2(1,'u') f2(0,'l') f6('yu',3,2) f3() f2(3,'b') f6('aim',1,2) f4('i') f2(6,'g') f5('d',2) f7() main()

30 For loop: Another loop type
We use For loops when we know exactly how many times the loop will occur A subset of while 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())

31 More for loops: def f(): for x in [1,3,5,7,9]: print(x) return(x)
print(f()) for x in [2,7,1,9,4]:

32 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())

33 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"))

34 More for loops: def f(): for x in [0,1,2,3,4]: print(x) return(x)
print(f()) Shortcut: using range for x in range(5): # range(5) = [0,1,2,3,4]

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

36 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()) for x in range(-3,3,2): # from -3 up to but not including 3, by increments of 2, e.g., [-3,-1,1] (Can we make a loop go backwards?)

37 What do these 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"])) def f(v): var1 = "" for x in range(len(v) - 1,-1,-2): var1 += v[x] return(var1) print(f("kebijrtese"))

38 This one? def f(): strvar = input("enter a number: ") y = 1 z = 0 var1 = "" for x in range(len(strvar)-1,-1,-1): z += int(strvar[x]) * y y*=10 return(z) print(f()) def f(lv): x = len(lv) print(x) for y in range(0,x): if "t" in lv[y]: print(lv[y]) return listvar = ["ham","am","boat","goat","there","anywhere"] f(listvar)

39 How about this one? def f(word): newstr = "" for i in range(1,len(word)+1): newstr += word[-i] return(newstr) wvar = "live" print(f(wvar))

40 What does this do? def f(word): high = len(word) low = 0 newstr = ""
for i in range(10): position = randrange(low, high) newstr += word[position] return(newstr) wvar = “turkey" print(f(wvar))

41 What do you get? def f(message): newmessage = "" for x in message:
if x == "g": newmessage += "l" else: newmessage += x return(newmessage) mvar = "pogysyggabicaggy" print("new string: " + f(mvar))

42 def fun4(m): z = "" for s in range(len(m)): for y in range(1,len(m[s]),2): z += m[s][y] return(z) ls = [['d','a','r','c','y'],['d','o','o','r'],['a','n','d']] print(fun4(ls))

43 Lists of Lists – Matrices:
def k(m,n): v = [] for x in range(m): ls = [] for y in range(n): ls.append(0) v.append(ls) return(v) m = k(4,5) #what is this? for x in range(4): print(m[x])

44 Accessing a matrix First, access which list, and then which value in that list: E.g., def makemat(): mat = [[3,2,1,4],[1,4,2,3],[3,3,3,3]] print(mat[1][2]) #prints 2 makemat() 3 2 1 4

45 Add 1 to the matrix in a random place?
def p(x,m): i = 0 while (i ==0): #why didn’t I use a for loop here? b = randrange(len(m)) c = randrange(len(m[b])) if m[b][c] != 1: m[b][c] = 1 i= 1 return(m) m = p(7,m)

46 Print out the matrix: Print out matrix with tabs between each num in each row, e.g.,: def q(m): for x in range(len(m)): for y in range(len(m[x])): print(m[x][y],end = "\t") print() return q(m)


Download ppt "Lists: a new type! LISTS! sets of a thing (e.g., sets of ints)"

Similar presentations


Ads by Google