15-110: Principles of Computing

Slides:



Advertisements
Similar presentations
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.
Advertisements

Guide to Programming with Python
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.
Python Dictionary.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
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.
Data Structures Akshay Singh.  Lists in python can contain any data type  Declaring a list:  a = [‘random’,’variable’, 1, 2]
Python Programming Chapter 10: Dictionaries 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.
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.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
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.
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.
Built-in Data Structures in Python An Introduction.
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.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
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.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
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.
Lesson 3 Functions. Lesson 3 Functions are declared with function. For example, to calculate the cube of a number function function name (parameters)
String and Lists Dr. José M. Reyes Álamo.
10 - Python Dictionary John R. Woodward.
Tuples and Lists.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
Intro to Computer Science CS1510 Dr. Sarah Diesburg
COSC 1323 – Computer Science Concepts I
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
8 – Lists and tuples John R. Woodward.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Dictionaries Dictionary: object that stores a collection of data
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
15-110: Principles of Computing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
15-110: Principles of Computing
15-110: Principles of Computing
15-110: Principles of Computing
15-110: Principles of Computing
By- Anshul Kumar Class: XI “B”
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Dictionary.
Python List.
Control flow: Loops UW CSE 160.
Tuple.
Introduction to Computer Science
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

15-110: Principles of Computing Sequences- Part IV (Tuples and Dictionaries) Lecture 15, October 23, 2018 Mohammad Hammoud Carnegie Mellon University in Qatar

Today… Last Session: Today’s Session: Sequences- Part III (Matrix Operations as an Application on Lists) Today’s Session: Sequences- Part IV: Tuples Dictionaries

Tuples Tuples are very similar to lists, but they are immutable (i.e., unchangeable) Tuples are written with round brackets as follows: t1 = (1, 2, 3) t2 = (“a”, “b”, “c”, ”d”) t3 = (200, “A”, [4, 5], 3.2) print(t1) print(t2) print(t3)

Tuples Like lists, tuples can: Contain any and different types of elements Contain duplicate elements (e.g., (1, 1, 2)) Be indexed exactly in the same way (i.e., using the [] brackets) Be sliced exactly in the same way (i.e., using the [::] notation) Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”)) Be repeated (e.g., t = (“a”, “b”) * 10) Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4)) Be passed to a function, but will result in pass-by-value and not pass-by- reference outcome since it is immutable Be iterated over

Examples This will print the elements of t1 in a reversed order, but will not change t1 itself since it is immutable t1 = ("a", "b", "c") print(t1[::-1]) t2 = ("a", "b", "c") t3 = t1 + t2 print(t3) t3 = t3 * 4 for i in t3: print(i, end = " ") print() This will concatenate t1 and t2 and assign the result to t3 (again, t1 and t2 will be unchanged since they are immutable) This will repeat t3 four times and assign the result to t3. Hence, t3 will be overwritten (i.e., NOT changed in place- because it is immutable-, but redefined with a new value)

Examples This is an example of nesting, where a matrix with 2 rows and 3 columns is created. The first row includes the elements 1, 2, and 3. The second row includes the elements “a”, “b”, and “c”. t4 = ((1, 2, 3), ("a", "b", "c")) for j in t4: for k in j: print(k,end = " ") print() This outer loop iterates over each element in t4; that is, it gets first the element (1, 2, 3) and second the element (“a”, “b”, “c”) This inner loop iterates over each element read by the outer loop; that is, it first iterates over the elements of the element (1, 2, 3), and second it iterates over the elements of the element (“a”, “b”, “c”)

Examples This change on t remains local to the function since a value of t was passed and not a reference to it def func1(t): t = t * 2 t = (1, 2, 3) print(t) func1(t) This will output (1, 2, 3) This will also output (1, 2, 3) since tuples are immutable, hence, will always exhibit a passed-by-value behavior

Using Functions with Tuples You can also use functions with tuples The count(x) function returns the number of elements with the specified value x (e.g., x is 1 in this example) t1 = (1, 2, 3, 1, 5, 1) print(t1.count(1)) print(t1.index(1)) Output: 3 The index(x) function returns the index of the first element with the specified value x (e.g., x is 1 in this example) In fact, Python has only these two built-in functions that can be used on tuples

Towards Dictionaries Lists and tuples hold elements with only integer indices So in essence, each element has an index (or a key) which can only be an integer, and a value which can be of any type (e.g., in the above list/tuple, the first element has key 0 and value 45) What if we want to store elements with non-integer indices (or keys)? 45 “Coding” 4.5 7 89 Integer Indices 1 2 3 4

Dictionaries In Python, you can use a dictionary to store elements with keys of any types (not necessarily only integers like lists and tuples) and values of any types as well The above dictionary can be defined in Python as follows: dic = {"NUM":45, 1000:"coding", 2000:4.5, 3.4:7, "XXX":89} 45 “Coding” 4.5 7 89 “NUM” 1000 2000 3.4 “XXX” keys of different types Values of different types key value Each element is a key:value pair, and elements are separated by commas

Dictionaries In summary, dictionaries: Can contain any and different types of elements (i.e., keys and values) Can contain only unique keys but duplicate values Can be indexed but only through keys (i.e., dic2[“a”] will return 1 but dic2[0] will return an error since there is no element with key 0 in dic2 above) dic2 = {"a":1, "a":2, "b":2} print(dic2) Output: {'a': 2, 'b': 2} The element “a”:2 will override the element “a”:1 because only ONE element can have key “a”

Dictionaries In summary, dictionaries: CANNOT be concatenated CANNOT be repeated Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}} Can be passed to a function and will result in a pass-by-reference and not pass-by-value behavior since it is immutable (like lists) def func1(d): d["first"] = [1, 2, 3] dic = {"first":{1:1}, "second":{2:"a"}} print(dic) func1(dic) Output: {'first': {1: 1}, 'second': {2: 'a'}} {'first': [1, 2, 3], 'second': {2: 'a'}}

Dictionaries In summary, dictionaries: Can be iterated over dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(i) first second third ONLY the keys will be returned. Output: How to get the values?

Dictionaries In summary, dictionaries: Can be iterated over dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(dic[i]) 1 2 3 Output: Values can be accessed via indexing!

Adding Elements to a Dictionary How to add elements to a dictionary? By indexing the dictionary via a key and assigning a corresponding value dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} Output:

Adding Elements to a Dictionary How to add elements to a dictionary? By indexing the dictionary via a key and assigning a corresponding value dic = {"first": 1, "second": 2, "third": 3} print(dic) dic[”second"] = 4 If the key already exists, the value will be overridden {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second’: 4, 'third': 3} Output:

Deleting Elements to a Dictionary How to delete elements in a dictionary? By using del dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 del dic["first"] Output: {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} {'second': 2, 'third': 3, 'fourth': 4}

Deleting Elements to a Dictionary How to delete elements in a dictionary? Or by using the function pop(key) dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 dic.pop(“first”) Output: {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} {'second': 2, 'third': 3, 'fourth': 4}

Dictionary Functions Many other functions can also be used with dictionaries Function Description dic.clear() Removes all the elements from dictionary dic dic.copy() Returns a copy of dictionary dic dic.items() Returns a list containing a tuple for each key-value pair in dictionary dic dic.get(k) Returns the value of the specified key k from dictionary dic dic.keys() Returns a list containing all the keys of dictionary dic dic.pop(k) Removes the element with the specified key k from dictionary dic

Dictionary Functions Many other functions can also be used with dictionaries Function Description dic.popitem() Removes the last inserted key-value pair in dictionary dic dic.values() Returns a list of all the values in dictionary dic

Next Lecture… Practice on Tuples and Dictionaries