INTRO2CS Tirgul 4 1. What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

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:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Tuples. Tuples 1 A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference is that tuples can't be.
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.
Introduction to C Programming
Lists Introduction to Computing Science and Programming I.
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
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.
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Python Crash Course Containers 3 rd year Bachelors V1.0 dd Hour 3.
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.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
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.
12/9/2010 Course A201: Introduction to Programming.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Lists CS303E: Elements of Computers and Programming.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
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.
LECTURE 5 Strings. STRINGS We’ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type. Strings are.
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.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Intro2cs Tirgul 4.
String and Lists Dr. José M. Reyes Álamo.
Intro2cs Tirgul 3.
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
CS 100: Roadmap to Computing
String Processing Upsorn Praphamontripong CS 1110
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Bryan Burlingame 03 October 2018
CHAPTER THREE Sequences.
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.
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Basic String Operations
CHAPTER 3: String And Numeric Data In Python
CS 1111 Introduction to Programming Spring 2019
Topics Sequences Lists Copying Lists Processing Lists
CISC101 Reminders Assignment 2 due today.
Topics Basic String Operations String Slicing
CHAPTER 4: Lists, Tuples and Dictionaries
Introduction to Computer Science
Topics Sequences Introduction to Lists List Slicing
Python Review
Topics Basic String Operations String Slicing
For loop Using lists.
Topics Basic String Operations String Slicing
Introduction to Computer Science
Presentation transcript:

INTRO2CS Tirgul 4 1

What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and Deep Copy 2

Remarks from ex2 tests 3  Use the README template from the course homepage!  MAKE SURE YOU NAME THE README FILE README (and not Readme / README.txt,…)  For constants use capital letters and underscore for separation. For example: MAX_LENGTH = 100 HEIGHT = 36 NUMBER_OF_ CHILDREN = 17

Remarks from ex2 tests 4  No need to use constants in the following case: perimeter = TWO * pi * r In this case you should write the number as is: perimeter = 2 * pi * r  Choose informative names for constants!  An example of bad names: ONE = 1 # stands for rectangle TWO = 2 # stands for circle THREE = 3 # stands for triangle  An example of good names: RECTANGLE = 1 CIRCLE = 2 TRIANGLE = 3

Sequences (1) 5  The most basic data structure in Python is the sequence.  Each element of a sequence is assigned a number - its position or index.  The first index is zero, the second index is one, and so on.

Sequences (2)  Python has several types of sequences, for example: list, tuple, str, range.  All share the following features: Each sequence contains a finite number of elements. The elements are arranged in some order in the sequence. It is possible to iterate over the elements in the sequence, according to their order. It is also possible to check if an element is in a sequence. 6

Sequences (3) 7  There are certain things you can do with all sequence types.  These operations include indexing, slicing, adding, multiplying, and checking for membership.  In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements, as we will see later.

Mutable and Immutable 8  The value of some objects can be changed.  Objects whose value can be changed are said to be mutable;  objects whose value is unchangeable once they are created are called immutable.  An object’s mutability is determined by its type; for instance, numbers, strings, ranges and tuples are immutable, while lists are mutable.

Strings  A string is a sequence of characters.  Python does not support a ‘character’ type; these are treated as strings of length one, thus also considered a substring. For example: ‘a’, ‘b’, ‘c’  Creating strings is as simple as assigning a value to a variable. For example: 9

Triple Quotes (1)  Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.  The syntax for triple quotes consists of three consecutive single or double quotes. 10

Triple Quotes (2) 11

Access a character in a string  To access a character in a string, use the square brackets along with the index: [index], to obtain your substring.  Following is a simple example: 12

Range Slicing  In the same way we access a single character in a string, we can also access a substring of a string, containing multiple characters.  This operation where we access a substring of a string, called slicing.  Here, too, we will use the square brackets, along with the indices we want to take from the string. 13

Updating Strings  You can "update" an existing string by (re)assigning a variable to another string.  The new value can be related to its previous value or to a completely different string altogether. 14

String Special Operators OperatorDescriptionExampleoutput Concatenation - Adds values on either side of the operator HelloPython + Repetition - Creates new strings, concatenating multiple copies of the same string * [ ]Slice - Gives the character from the given index e a[1] Range Slice - Gives the characters from the given range [ : ] a[1:4] ell in not in Membership - Returns true if a character exists in the given string H in a True Membership - Returns true if a character does not exist in the given string M not in a True a+b a*2 HelloHello 15

Iterating over a string 16

Built-in String Methods (1)  Python includes the following built-in methods to manipulate strings:  rfind(str, beg=0,end=len(string)) Same as find(), but search backwards in string rfind(str, beg=0,end=len(string))  capitalize() Capitalizes first letter of string capitalize()  count(str, beg= 0,end=len(string)) Counts how many times str occurs in string or in a substring of string if starting count(str, beg= 0,end=len(string)) index beg and ending index end are given  endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending endswith(suffix, beg=0, end=len(string)) index end are given) ends with suffix; returns true if so and false otherwise  find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise find(str, beg=0 end=len(string))  index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found index(str, beg=0, end=len(string)) 17

isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwiseisalpha() isdigit() Returns true if string contains only digits and false otherwiseisdigit() islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwiseislower() isnumeric() Returns true if a unicode string contains only numeric characters and false otherwiseisnumeric() len(string) Returns the length of the stringlen(string) lower() Converts all uppercase letters in string to lowercaselower() Built-in String Methods (2) 18

Built-in String Methods (3)  replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max occurrences if max given replace(old, new [, max])  upper() Converts lowercase letters in string to uppercase upper()  And more…..  More about python strings: 19

Python Lists 20  The list is the most versatile data type available in Python, which can be written as a list of comma-separated values (items) between square brackets: [ ]  Good thing about a list is that items in a list do not need to have the same type.

Lists can hold different types lst = [1,3,'hi','bye']  be cautious!  Can you think of an example of what may go wrong? 21

Creating a list (1) 22  Creating a list is as simple as putting different comma-separated values between square brackets.  For example:  Like string indices, list indices start at 0  Lists can be sliced, concatenated and so on.

Creating a list (1) 23  Another way to create a list is by using the ‘list()’ method. list(seq) - Converts a sequence into list.

Accessing Values in Lists 24  To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.

List Slicing (1)  Slicing will create a new list with a subset of the original list.  Works very similar to ‘range’ lst1 = lst[start:end] # items from start through end-1 lst2 = lst[start:] # items from start through the rest of the list 25

List Slicing (2)  Slicing will create a new list with a subset of the original list lst3 = lst[:end] # items from the beginning through end-1 lst4 = lst[start:end:step] # start through not past end, by step lst5 =lst[::step] # from the beginning to the end by step 26

Updating Lists (1) 27  You can update single or multiple elements of a list by giving the slice on the left-hand side of the assignment operator, and the new values on the right-hand side.

Updating Lists (2) 28  You can also add elements to a list by using the append() method: list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].  append() takes exactly one argument!

Updating Lists (3) 29  You can also extend a list by using the extend() method: list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

Delete List Elements 30  To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting, or the remove() method if you do not know.

Basic List Operations 31  Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too.  In fact, lists respond to all of the general sequence operations we used on strings. Python ExpressionResultsDescription len([1, 2, 3]) 3Length [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation ['Hi!‘] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!‘]Repetition MembershipTrue 3 in [1, 2, 3] for x in [1, 2, 3]: print x, Iteration 1 2 3

Indexing and Slicing 32  Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.  Assuming following input: Python ExpressionResultsExplanation L[2] L[-2] L[1:] 'SPAM!' 'Spam' ['Spam', 'SPAM!'] Offsets start at zero Negative: count from the right Slicing fetches sections

Built-in List Functions 33  len(list) Gives the total length of the list. len(list)  max(list) Returns item from the list with max value. max(list)  min(list) Returns item from the list with min value. min(list)  list(seq) Converts a tuple into list. list(seq)

Built-in List Methods (1) 34  list.append(obj) Appends object obj to list list.append(obj)  list.count(obj) Returns count of how many times obj occurs in list list.count(obj)  list.extend(seq) Appends the contents of seq to list list.extend(seq)  list.index(obj) Returns the lowest index in list that obj appears list.index(obj)  list.insert(index, obj) Inserts object obj into list at offset index list.insert(index, obj)

Built-in List Methods (2) 35  list.pop(obj=list[-1]) Removes and returns last object or obj from list list.pop(obj=list[-1])  list.remove(obj) Remove the first item from the list whose value is x. It is an error if there is no such item. list.remove(obj)  list.reverse() Reverses objects of list in place list.reverse()  list.sort([func]) Sorts objects of list, use compare func if given list.sort([func])  More about list methods: #more-on-lists #more-on-lists

An example that uses most of the list methods (1) 36 >>> a = [66.25, 333, 333, 1, ] >>> print( a.count (333), a.count (66.25), a.count ('x')) >>> a.insert (2, - 1) >>> a.append (333) >>> a [66.25, 333, -1, 333, 1, , 333] >>> a.index (333) 1

An example that uses most of the list methods (2) 37 >>> a.remove (333) >>> a [66.25, -1, 333, 1, , 333] >>> a.reverse () >>> a [333, , 1, 333, -1, 66.25] >>> a.sort () >>> a [-1, 1, 66.25, 333, 333, ] >>> a.pop () >>> a [-1, 1, 66.25, 333, 333]

Iterating over a list (1) 38

Iterating over a list (2) – an important comment 39  What’s the difference between: for i in range(len(lst)): lst[i] = lst[i]*2 And for i in lst: i =i*2

Python Tuples  A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.  The only differences are that tuples can't be changed i.e., tuples are immutable, and tuples use parentheses instead of square brackets in lists. 40

Creating a tuple (1)  Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also.  For example: 41

Creating a tuple (2)  To write a tuple containing a single value you have to include a comma, even though there is only one value:  The empty tuple is written as two parentheses containing nothing: 42

Accessing Values in Tuples 43  Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.  To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.

Updating Tuples 44  Tuples are immutable which means you cannot update or change the values of tuple elements.  You are able to take portions of existing tuples to create new tuples, as the following example demonstrates:

Delete Tuple Elements (1) 45  Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.  To explicitly remove an entire tuple, just use the del statement.

Delete Tuple Elements (2) 46  This will produce following result.  Note an exception is raised, because after del tup, the tuple ‘tup’ does not exist anymore:

Basic Tuples Operations 47  Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too.  In fact, tuples respond to all of the general sequence operations we used on strings. Python ExpressionResultsDescription len((1, 2, 3)) 3Length (1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)Concatenation ('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')Repetition MembershipTrue 3 in (1, 2, 3) for x in (1, 2, 3): print x, Iteration 1 2 3

Indexing and Slicing 48  Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings.  Assuming following input: Python ExpressionResultsExplanation L[2] L[-2] L[1:] 'SPAM!' 'Spam' ['Spam', 'SPAM!'] Offsets start at zero Negative: count from the right Slicing fetches sections

No Enclosing Delimiters (1) 49  Any set of multiple objects, comma-separated, written without identifying symbols (i.e., brackets for lists, parentheses for tuples, etc.), default to tuples.

No Enclosing Delimiters (2) 50  An example in python shell: Underscore (‘_’) gets the last answer in the python shell

Built-in Tuple Functions 51  len(tuple) Gives the total length of the tuple. len(tuple)  max(tuple) Returns item from the tuple with max value. max(tuple)  min(tuple) Returns item from the tuple with min value. min(tuple)  tuple(seq) Converts a list into tuple. tuple(seq)

Mutable and Immutable 52 objectMutable or Immutable? numbers string range tuple lists Immutable mutable

Immutable container – a comment 53  The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed.  However, the container is still considered immutable, because the collection of objects it contains cannot be changed.  So, immutability is not strictly the same as having an unchangeable value, it is more subtle.

Sequences go well with loops 54

Summing a range 55 What will be printed?

Nested for loops  For loops may be nested, that is you can put a for loop inside another for loop  A nested loop is a loop within a loop, an inner loop within the body of an outer one.  How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion.  Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop is ended. 56

Nested loops, why is it useful?  How to print 8 rows of 5 stars each? for i in range(8): for k in range(5): print('*', end='') print() ***** The truth is that it could be done simpler: for i in range(8): print('*'*5) 57

Multiplication table How do you print the multiplication table? (Up to 100) 58

Multiplication table for i in range(1, 11): for j in range(1, 11): print(i*j, end='\t') print() 59

nested loops How can we print the following series using nested loops?

Print range of ranges for i in range(1, 6): for j in range(1, i+1): print(j, end=" ") print() 61

Iterating over a list of lists 62 What will be printed?

List of tuples and lists 63 What will be printed?

Nested for loops 64 What are we trying to do here? What will be printed? We performed a sort of the list, by a method called “Bubble Sort”

Shallow and Deep Copy  B=A Shallow copy  In the process of shallow copying A, B will copy all of A's field values. If the field value is a memory address it copies the memory address, and if the field value is a object that is not containers: int, float, bool (primitive type) - it copies the value of it. Deep copy  In deep copy the data is actually copied over. The result is different from the result a shallow copy gives. The advantage is that A and B do not depend on each other, but at the cost of a slower and more expensive copy. 65

Copying a list  Assign a list to another # a new list is assigned to colours2. 66

Copying a list  Assign a list to another 67

Copy with the equal operator The id function: Returns the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. 68

Copy with the slice operator Simple data types 69

Copy with the slice operator  Compound data types 70

deepcopy from the Module copy 71