Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "INTRO2CS Tirgul 4 1. What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and."— Presentation transcript:

1 INTRO2CS Tirgul 4 1

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

3 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

4 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

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

6 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

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

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

9 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

10 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

11 Triple Quotes (2) 11

12 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

13 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

14 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

15 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

16 Iterating over a string 16

17 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

18 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

19 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: http://www.tutorialspoint.com/python/python_strings.htm 19

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

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

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

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

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

25 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

26 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

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

28 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!

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

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

31 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

32 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

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

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

35 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: https://docs.python.org/2/tutorial/datastructures.html #more-on-lists https://docs.python.org/2/tutorial/datastructures.html #more-on-lists

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

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

38 Iterating over a list (1) 38

39 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

40 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

41 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

42 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

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

44 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:

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

46 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:

47 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

48 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

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

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

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

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

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

54 Sequences go well with loops 54

55 Summing a range 55 What will be printed?

56 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

57 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

58 Multiplication table 12345678910 2468101214161820 36912151821242730 481216202428323640 5101520253035404550 6121824303642485460 7142128354249566370 8162432404856647280 9182736455463728190 102030405060708090100 How do you print the multiplication table? (Up to 100) 58

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

60 nested loops How can we print the following series using nested loops? 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 60

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

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

63 List of tuples and lists 63 What will be printed?

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

65 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

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

67 Copying a list  Assign a list to another 67

68 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

69 Copy with the slice operator Simple data types 69

70 Copy with the slice operator  Compound data types 70

71 deepcopy from the Module copy 71


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

Similar presentations


Ads by Google