Intro to Robots Lists in Python. Intro to Robots What is a List? An ordered set of values: –Ordered: 1 st, 2 nd, 3 rd, … –Values: can be anything, integers,

Slides:



Advertisements
Similar presentations
Python Mini-Course University of Oklahoma Department of Psychology
Advertisements

ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Course A201: Introduction to Programming 10/28/2010.
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?
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Python Programming Chapter 9: Tuples Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
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.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Lists Introduction to Computing Science and Programming I.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Lists/Tuples. Example Write a program to keep track of all students’ scores on exam 1. Need a list of everyone’s score Use 14 doubles What about next.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Programming for Linguists An Introduction to Python 24/11/2011.
Python Programming Chapter 8: Lists Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
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.
Programming in Python Part III Dr. Fatma Cemile Serçe Atılım University
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
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.
Python Tricks CMSC 201. Overview Today we are learning some new tricks to make our lives easier! Slicing and other tricks Multiple return values Global.
CIT 590 Intro to Programming Lecture 5 – completing lists.
12/9/2010 Course A201: Introduction to Programming.
Math 15 Introduction to Scientific Data Analysis Lecture 8 Python Programming – Part 2 University of California, Merced.
I Power Higher Computing Software Development High Level Language Constructs.
Course A201: Introduction to Programming 09/30/2010.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
CIT 590 Intro to Programming Lecture 4. How are assignments evaluated Pay attention to what the HW says it is trying to teach you about ‘modular programming’
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
CPSC 217 T03 Week IX Part #1: Function, Iteration and List Hubert (Sathaporn) Hu.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
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.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
CMSC201 Computer Science I for Majors Lecture 08 – Lists
String and Lists Dr. José M. Reyes Álamo.
Data types: Complex types (List)
Module 4 String and list – String traversal and comparison with examples, List operation with example, Tuples and Dictionaries-Operations and examples.
Containers and Lists CIS 40 – Introduction to Programming in Python
From Think Python How to Think Like a Computer Scientist
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
Lists in Python.
Creation, Traversal, Insertion and Removal
Data types Numeric types Sequence types float int bool list str
Lists A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are.
String and Lists Dr. José M. Reyes Álamo.
Lists Part 1 Taken from notes by Dr. Neil Moore
CS1110 Today: collections.
By- Anshul Kumar Class: XI “B”
And now for something completely different . . .
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Presentation transcript:

Intro to Robots Lists in Python

Intro to Robots What is a List? An ordered set of values: –Ordered: 1 st, 2 nd, 3 rd, … –Values: can be anything, integers, strings, other lists List values are called elements. A string is an ordered set of characters so it is “like” a list but not exactly the same thing.

Intro to Robots Create a new List: Assignment: Calling the range() function: x = [1,5,’egg’,[2,3]] A couple of integers, a string and a “nested” list, all in the same list. y = range(5) print y [1, 2, 3, 4] range(a) returns all the integers from 0 to a-1 y = range(1,5) print y [1, 2, 3, 4] range(a,b) returns all the integers from a to b, including a, excluding b. y = range(1,15,2) print y [1, 2, 3, 4] range(a,b,c) returns all the integers a, a+c, a+2c, …up to b, including a, excluding b.

Intro to Robots The Empty List The empty list is usually used to initialize a list variable but not give it any useful elements. x = [ ]

Intro to Robots Accessing Elements: List elements are accessed via integer indexes starting at 0 and working up. numbers = [ 3, 87, 43] print numbers[1], numbers[2], numbers[0] x = 3 print numbers[x-2] 87 Print numbers[1.0] TypeError: sequence index must be integer print numbers[3] TypeError: list index out of range print numbers[-1] # a negative index counts back 3 # from the end of the list # index -1 is the last element print numbers[-3] TypeError: list index out of range

Intro to Robots Accessing Many Elements: By index value, one at a time (called list traversal) # list of a known size horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’] i = 0 while i < 4: print horsemen[i] i = i + 1 # or if you don’t know how long the list is i = 0 length = len(horsemen) while i < length: print horsemen[i] i = i + 1 war famine pestilence death always safer to use len as an upper bound always I < length; never I <= length

Intro to Robots List Membership: You simply ask if a value is “in” or “not in” a list. This is always a True/False question. horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’] if ‘debauchery’ in horseman: print ‘There are more than 4 horsemen of the apocolipse. print ‘debauchery’ not in horsemen 1

Intro to Robots Loop Operator for Lists We have already seen that a while-loop can be used to “traverse” a list. There is also a special for-loop notation. Exercise: Print out a list of ten 0s and 1s. horsemen = [‘war’, ‘famine’, ‘pestilence’, ‘death’] for horseman in horsemen: print horseman a different variable for x in range(20): print x%2

Intro to Robots List Operations: Add two lists: Repeat a list many times: Exercise: Create a list of 20 zeros. a = [1, 2, 3] b = [4, 5, 6] c = a + b print c [1, 2, 3, 4,5, 6] a = [1, 2, 3] print a*3 [1, 2, 3, 1, 2, 3, 1, 2, 3] zeros = [0]*20

Intro to Robots List Slices: Sometimes you just want a sub-list (slice) of a list. Exercise: What does vowels[:3] mean? list[a:b] means list[a], list[a+1], …, list[b-1] # all list elements with indexes from a to b; # including a and excluding b vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] print vowels[2:4] [‘i’, ‘o’] # how do you print out the last element? print vowels[2:] [‘i’, ‘o’, ‘u’] [‘a’, ‘e’, ‘i’]

Intro to Robots Exercise: What does [:] mean? >>> print vowels[:] [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

Intro to Robots Lists are Mutable (Their values can change): However it gets trickier when you try to add something to a list and not just replace something... fruit = [‘apple’, ‘orange’, ‘pear’] fruit[1] = ‘fig’ print fruit [‘apple’, ‘fig’, ‘pear’]

Intro to Robots List Slices Used to Modify a List: Suppose you are keeping an ordered list: And you want to add kate. Assignment doesn’t work! You can add an element by squeezing it into an empty slice between two list elements: names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] names[2] = ‘kate’ print names [‘adam’, ‘carol’, ‘kate’, ‘margot’, ‘phil’] names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] names[2:2] = ‘kate’ print names [‘adam’, ‘carol’, ‘henry’, ‘kate’, ‘margot’, ‘phil’] Starting at index 2 but not including 2; ie, empty

Intro to Robots List Deletion: Using the del operator Replacing an element with an empty list Deleting slices names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] del names[3] print names [‘adam’, ‘carol’, ‘henry’, ‘phil’] names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] names[3:4] = [ ] print names [‘adam’, ‘carol’, ‘henry’, ‘phil’] names = [‘adam’, ‘carol’, ‘henry’, ‘margot’, ‘phil’] del names[1:4] print names [‘adam’, ‘phil’]

Intro to Robots Objects and Values: Remember: So memory looks like: Two places in memory called x and y, both pointing to a place with a 3 stored in it. x = 3 y = 3 print id(x), id(y) xyxy

Intro to Robots Lists, Objects and Values Lists are different: So this time the memory state picture is: a = [1, 2, 3] b = [1, 2, 3] print id(a), id(b) [1, 2, 3] abab

Intro to Robots Lists, Objects and Values However, if we use assignment: So this time the memory state picture is: a = [1, 2, 3] b = [1, 2, 3] print id(a), id(b) [1, 2, 3] abab

Intro to Robots Aliasing However, if we assign one variable to another: So this time the memory state picture is: More importantly, changing b also changes a a = [1, 2, 3] b = a print id(a), id(b) [1, 2, 3] abab b[0] = 0 print a [0, 2, 3]

Intro to Robots Lists are like: Money: Or also Credit Cards: [1, 2, 3] my wallet my wife’s purse [1, 2, 3] me my wife

Intro to Robots Cloning a List: Cloning means making an exact but separate copy: Not Cloning: Cloning: a = [1, 2, 3] b = a print id(a), id(b) a = [1, 2, 3] b = a[:] # slices are always separate lists print id(a), id(b)

Intro to Robots List Parameters: We create a function and we pass a list as its argument. def head(lst): # returns the first element of a list return lst[0] # list remains unchanged. numbers = [1, 2, 3] x = head(numbers) print x print numbers 1 [1, 2, 3] numbers lst __main__ head

Intro to Robots Changing List Arguments: def tail(lst): return lst[1:] numbers = [1,2,3] rest = tail(numbers) print numbers [1,2,3] print rest [2,3] def deleteHead(lst): del lst[0] numbers = [1,2,3] deleteHead(numbers) print numbers [2,3]

Intro to Robots Lists and Strings: The String module has very useful list functions. Suppose we have And we want There is a string function that will split up a string into a list of tokens. ‘The rain in Spain falls mainly in the plane’ [‘The’, ‘rain’, ‘in’, ‘Spain’, ‘falls’, ‘mainly’, ‘in’, ‘the’, ‘plane’] str = ‘The rain in Spain falls mainly in the plane’ tokens = string.split(str) print tokens [‘The’, ‘rain’, ‘in’, ‘Spain’, ‘falls’, ‘mainly’, ‘in’, ‘the’, ‘plane’]

Intro to Robots Lists and Strings: The opposite to string.split() is string.join(). tokens = [‘The’, ‘rain’, ‘in’, ‘Spain’, ‘falls’, ‘mainly’, ‘in’, ‘the’, ‘plane’] str = string.join(tokens,‘ ‘) print str ‘The rain in Spain falls mainly in the plane’ join( ) will join tokens with whatever separator you wish to use. In this case the separator is a space ‘ ‘.

Intro to Robots Exercise: Suppose you know that “The Bakery” in New Paltz has a web site and that the website name is some variation of But it could be any one of Write Python code that will take the first string as input and print out the three final strings. (Wouldn’t this be a nice feature for your browser?) “I love the bakery”