CHAPTER THREE Sequences.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
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.
JavaScript, Third Edition
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.
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.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
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.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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 TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
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.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
28 Formatted Output.
String and Lists Dr. José M. Reyes Álamo.
Definition of the Programming Language CPRL
Python Variable Types.
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Working with Collections of Data
© 2016 Pearson Education, Ltd. All rights reserved.
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CSc 120 Introduction to Computer Programing II
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Strings Part 1 Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 this week.
Introduction to Strings
Chapter 7: Strings and Characters
Bryan Burlingame Halloween 2018
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
8 – Lists and tuples John R. Woodward.
Object Oriented Programming in java
String and Lists Dr. José M. Reyes Álamo.
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Presented by Mirza Elahi 10/29/2018
Ruth Anderson UW CSE 160 Winter 2017
Topics Sequences Introduction to Lists List Slicing
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Python Primer 1: Types and Operators
Introduction to Strings
CS1110 Today: collections.
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
15-110: Principles of Computing
Introduction to Computer Science
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Introduction to Strings
Python Review
Ruth Anderson UW CSE 160 Spring 2018
Introduction to Strings
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Dictionary.
Introduction to Computer Science
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

CHAPTER THREE Sequences

Sequences contains objects that are kept in a specific order you can identify an object in a sequence by its index location the first object in a sequence is zero when a sequence is referenced outside its range, an exception is raised a variable contains zero or one value a sequence can contain zero or many values you can extract from a sequence with the slicing operation examples of sequences include lists, tuples and strings

Sequences Operations on sequences Three common operations applied to sequences + will concatenate sequences to make them longer * is used with numerical digits to repeat the sequence several times [ ] fetches a particular element from the sequence(index) or a subset of elements (slicing)

Strings (immutable or static ) Definition a sequence that contains single-byte ASCII characters used to store and represent text information can be enclosed in single ('), double (") or triple quotes (''' or """) as follows: o = ‘Lets party’ OR o = “Lets party” OR o = '''Lets party''' are immutable, cannot modify an existing string object an operation on a string object creates a new string object

Strings (immutable or static ) Displaying strings newline e.g k="Hello World!\nIt's hot continuation e.g k="Hello World!\ It's hot“ Single quote use escape character e.g k='Isn\'t it?‘ If double quotes no need for \ e.g k="Isn't it? " In a triple quoted string, line breaks in the literal are preserved as newline characters. You cannot use a backslash in a triple-quoted string

Strings (immutable or static ) How characters are stored in a string Example s = “Mi” each character is stored at a specific index location a character is accessed through the index e.g. s[0] is M there is no separate data type for characters a character is a string of length 1

Strings (immutable or static ) String methods to view a list of all methods that can be used with str type help(‘str’)

Strings (immutable or static ) String methods (cont)

Strings (immutable or static ) Finding substrings in a string String Methods Used to Find Substrings in a String

Arrays Numerical arrays a string is an array of characters a numerical array stores numerical data they do not have NULL characters numerical arrays are NOT terminated by NULL characters indexes are used for accessing elements There are one and two dimensional arrays

Arrays One dimensional array given an array p as follows: array declaration : p= [ 0 for i in range(5) ] input into array : for i in range(5): p[i]= int(input()) print array values : for n in p: print (n)

Arrays Two dimensional array are divided into rows and columns The indices of row and column begin at value 0 To access each element of the array, you have to specify two indices; one for row, and the other for column Both are enclosed in square brackets. array declaration : p = [ [ 0 for i in range(3) ] for j in range(3) ] input into array : for d1 in range(3): for d2 in range(3): p[d1][d2]= int(input() print array value : p[1][2]

Lists (mutable) Definition is a container object that is mutable is a collection of elements, which might include other lists begin and end with a square bracket elements inside are separated with commas first element of the list is at index 0 last element is at index -1 Example: [p = ["John", "Kelly", 1, 2, [Sugar, Butter, 10]] #list containing a list print (p[0]) #prints John

Lists (mutable) Length of a list to find the length of a list, you use the len() function it returns the length as an index location of the last element plus one Given : names=['John', 'Kelly', 'Caroline', 'Paula'] len(names) will return 4 for i in range(0,len(names)): #range(0,4) returns 0 - 3 print (names[i])

Lists (mutable) List Slicing You can slice a list into parts to get desired elements Given : names=['John', 'Kelly', 'Caroline', 'Paula'] names[0:3] #returns index 0 to 2 ['John', 'Kelly', 'Caroline'] names[-4] #returns fourth from last ['John'] names[-3:-1]#returns third from last to second from last 'Kelly', 'Caroline'] names[:2] #returns first 2 ['John', 'Kelly'] names[2:] #returns index at 2 to last ['Caroline', 'Paula'] names[:-2] #returns index 0 to second from last ['John', 'Kelly', 'Caroline'] names[-2:] #returns second from last to end of the list ['Caroline', 'Paula']

Lists (mutable) Other list methods some of the methods that can be applied to lists

Tuples (immutable) Tuple objects are a type of sequence, like strings unlike strings, which can contain only characters tuples can contain elements of any type a tuple is an immutable object that cannot be changed once created as with every sequence, tuple indices are zero based the first element is at index 0, and the last element is at index -1 Is similar to a list, but elements are enclosed in parentheses () the elements are in a defined order

Tuples (immutable) Tuples vs Lists are faster than lists, when an item has to be added on the list a new one is created when defining a constant set of data, a tuple is preferred (write-protected) tuples can be used as dictionary keys. Dictionary keys must be immutable if tuples contain lists, then they can not be used as dictionary keys tuples can be converted into lists and vice versa

Tuples (immutable) Tuple example demonstration of a tuple names=('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')# declaration print ("The names in the tuple are:", names) # displayed as declared print ("The first name in the tuple is", names[0]) # John print ("The last name in the tuple is", names[len(names)-1])# Katherine print ("The names in the tuple are") for n in names: print (n) # John Kelly Caroline Steve Katheline

Dictionary (mutable) Dictionary a combination of key/value pairs in which every key has to be unique Key/value pairs are separated by a colon, and the pairs are separated by commas The key/value pairs are enclosed in a curly brackets Syntax d = {key1 : value1, key2 : value2 } dictionaries are mutable, which means a dictionary can be modified, and you don’t have to create a copy of it to modify it Dictionary keys are case sensitive and immutable because Python associates them with a unique number called a hash. Also, dictionary keys can be of mixed data types: strings, integers, and others.

Dictionary (mutable) Methods a some of the methods that can be applied to dictionary

Dictionary (mutable) Example illustration of a dictionary cap={'U.S.':'Washington D.C.','U.K.':'London','India':'New Delhi',} n=input('Enter country: ') if n in cap: print ('The capital of', n , 'is', cap[n]) else: print ('Sorry the country', n, 'does not exist in our dictionary') cap['Australia']='Sweden' print ('The dictionary after adding a country:') for country, capital in cap.items(): print ('Capital of', country, 'is' , capital) m=input('Enter the country to delete:') del cap[m] print ('The dictionary after deleting a country:')

Sets (mutable) The set container is an unordered collection of objects that can be contained in a hashtable hashtable is a set of key-value pairs since the sets are unordered, they do not support slicing or other sequence-like behaviour sets cannot have any duplicate elements an element only appears 0 or 1 times a set is mutable except a frozenset which is immutable

Sets (mutable) Uses of sets to tests membership to remove duplicates from a sequence to compute boolean operations like union , intersection, symmetric difference and set difference

Sets (mutable) Union (|) in a union operation an element appears in the union if it exists in one set or the other s1=set([3,5,6,10,11,100]) s2=set([1,3,5,6,11,15]) s1 | s2 s1.union (s2) returns {1,3,5,6,10,11,15,100}

Sets (mutable) Intersection (&) in an intersection operation, the elements that appear in both sets appear in the intersection s1=set([3,5,6,10,11,100]) s2=set([1,3,5,6,11,15]) s1& s2 s1.intersection (s2) returns {3,5,6,11}

Sets (mutable) Difference (-) In a difference operation, all the elements that are in the left set but not in the right set will appear in the difference operation s1=set([3,5,6,10,11,100]) s2=set([1,3,5,6,11,15]) s1-s2 s1.difference (s2) returns {10,100} s2-S1 s2.difference (s1) returns {1,15}

Sets (mutable) Symmetric difference (^) is the object that appears in one of the two sets provided but not in both s1=set([3,5,6,10,11,100]) s2=set([1,3,5,6,11,15]) s1.symmetric_difference (s2) returns {1,10,15,100}

Sets (mutable) Symmetric difference update symmetric_difference_update () method changes the first set to match the set that is returned by the function s1=set([3,5,6,10,11,100]) s2=set([1,3,5,6,11,15]) s1.symmetric_difference_update (s2) returns s1 as {1,10,15,100}

Sets (mutable) Membership to check if an object is in the set in is used s1=set([3,5,6,10,11,100]) s2=set([1,3,5,6,11,15]) 10 in s1 returns True 15 in s1 returns False 15 in s2 returns True

Sets (mutable) Iteration through a set makes it easy to iterate through distinct objects e.g s1=set([3,5,6,10,11,100]) for n in s: if ((n % 2 ) == 0) print (“%d is even” %n) else: print (“%d is odd” %n) Output: 3 is odd 5 is odd 6 is even 10 is even 11 is odd 100 is even

Sets (mutable) Removing objects from a set there are four functions to remove objects from a set pop () removes an object from a set. Object to be removed not specified remove () removes a specified object from a set discard () removes a specified object from a set. No error if object does not exist clear () clears the whole set completely

Sets (mutable) Set methods/functions The list of methods and functions that can be applied on a set

Notes