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)

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Def find_largest(x,y): largest = 0; count = 0; while count < x: rnum = randrange(0,y) if rnum > largest: largest = rnum count +=1 return(largest); print(find_largest(7,50))
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Lists Introduction to Computing Science and Programming I.
Def f(x): counter = 0 y = 0; while counter
List1 = ["gold", "gems ", "diamonds "] list2 = [“rubies", “emeralds ", “opals"] list3 = list1 + list2 print(list3) list1 +=list2 print(list1)
Def f(x): counter = 0 y = 0; while counter
30-Jun-15 Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s)
PPT3. Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Lists. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
Lists CS303E: Elements of Computers and Programming.
Strings:  Strings?  concatenate (join) +  make multiple copies using *  compare: > =
Largest of x random numbers def find_largest(x,y): largest = 0; count = 0; while count < x: rnum = randrange(0,y) if rnum > largest: largest = rnum count.
Lists COMPSCI 105 S Principles of Computer Science.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 10 Lists 1.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Python Programing: An Introduction to Computer Science
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
For loop: our last loop type
String and Lists Dr. José M. Reyes Álamo.
Scientific Programming in Python -- Cheat Sheet
Python - Lists.
CS 100: Roadmap to Computing
From Think Python How to Think Like a Computer Scientist
Chapter 10 Lists.
CSC 108H: Introduction to Computer Programming
CSC 108H: Introduction to Computer Programming
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
Bryan Burlingame 03 October 2018
Chapter 10 Lists.
8 – Lists and tuples John R. Woodward.
Data Structures – 1D Lists
CS 1111 Introduction to Programming Fall 2018
String and Lists Dr. José M. Reyes Álamo.
Chapter 5: Lists and Dictionaries
Lists Part 1 Taken from notes by Dr. Neil Moore
(more) Python.
CS 1111 Introduction to Programming Spring 2019
15-110: Principles of Computing
Lists.
More While Loops.
Lists: a new type! LISTS! sets of a thing (e.g., sets of ints)
Strings: Strings? concatenate (join) + make multiple copies using *
CSE 231 Lab 6.
For loop Using lists.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
COMPUTER SCIENCE PRESENTATION.
Introduction to Computer Science
Presentation transcript:

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)

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

LISTS: 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”

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.”)

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]

LISTS:SLICING (DIFFERENT FROM INDEXING) 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]) >>[”eye of newt”,”bat wing”]

SHORTCUTS Index: listvar2 = [“spider leg”,”toe of frog”,”eye of newt”, “bat wing”, “slug butter”,”snake dandruff”] Slice: 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”]

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

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

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.

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]

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

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

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

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

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

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

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…

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']))

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

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

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

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

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

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

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

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

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

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