CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

Similar documents
CIS192 Python Programming

CIS192: Python Programming

Python Programming: Lecture 2 Data Types

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

(CC)A-NC 2.5 by Randall Munroe Python

CSC148 Fall 2017 Ramp Up Session Reference

LECTURE 3 Python Basics Part 2

6. Data Types and Dynamic Typing (Cont.)

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS Summer 2013

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Python I. Some material adapted from Upenn cmpe391 slides and other sources

The Practice of Computing Using PYTHON

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

A Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015)

Algorithmic Thinking: Computing with Lists

MUTABLE LISTS AND DICTIONARIES 4

DSC 201: Data Analysis & Visualization

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Sequences and iteration in Python

Data Structures. Lists, Tuples, Sets, Dictionaries

A Brief Introduction to Python for those who know Java Last extensive revision: Jie Gao, Fall 2018 Previous revisions: Daniel Moroz, Fall 2015

Script language: Python Data structures

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

UNIVERSITY OF TORONTO SCARBOROUGH. Wnter 2016 EXAMINATIONS. CSC A20H Duration 2 hours 45 mins. No Aids Allowed

University of Texas at Arlington, TX, USA

Dictionaries. By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region. Based on CBSE Curriculum Class -11. Neha Tyagi, KV 5 Jaipur II Shift

Collections. Lists, Tuples, Sets, Dictionaries

Topic 7: Lists, Dictionaries and Strings

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS Advanced Unix Tools & Scripting

UNIVERSITY OF TORONTO SCARBOROUGH. December 2017 EXAMINATIONS. CSCA20H3 Duration 3 hours. Examination Aids: Instructor: Bretscher

Python Tutorial. Day 1

Introduction to Python! Lecture 2

Python: Short Overview and Recap

Programming in Python

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

MEIN 50010: Python Data Structures

Statements 2. a operator= b a = a operator b

MITOCW watch?v=rvrkt-jxvko

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

Python Evaluation Rules

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

Introduction to Python

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

CPD for GCSE Computing: Practical Sheet 6 February 14

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Some material adapted from Upenn cmpe391 slides and other sources

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

CSCA20 Worksheet Strings

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Introduction to String Manipulation

Lecture Agenda. Objects. But First... Immutable Types and Nesting. Immutable Types and Nesting

Notebook. March 30, 2019

AI Programming CS S-02 Python

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Question 1. December 2009 Final Examination Marking Scheme CSC 108 H1F

TUPLES AND RECURSIVE LISTS 5

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

1 Strings (Review) CS151: Problem Solving and Programming

Python for loops. Girls Programming Network School of Information Technologies University of Sydney. Mini-lecture 7

CS 11 python track: lecture 3. n Today: Useful coding idioms

Sets and Dictionaries. Modules and File I/O

Programming to Python

MULTIPLE CHOICE. Chapter Seven

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

Introduction to Python

Python Review IPRE

STATS Data Analysis using Python. Lecture 8: Hadoop and the mrjob package Some slides adapted from C. Budak

Beyond Blocks: Python Session #1

CIS192 Python Programming

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Programming Languages

More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Computational Integer Programming. Lecture 4: Python. Dr. Ted Ralphs

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 7. Fall 2018

CIS192: Python Programming

DSC 201: Data Analysis & Visualization

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

OOP and Scripting in Python Advanced Features

For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.

Introduction to Programming in Python (2)

An introduction introduction to functional functional programming programming using usin Haskell

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Transcription:

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 2 / 34

Creating a List list() and [] are both new empty lists Comma separated [1, 2, 3] and nested [[1, 2], [3, 4]] Construct from iterable list(range(3)) Concatenating two lists with + creates a new list. Lists are mutable Implemented as a resizable array in CPython (think ArrayList in Java) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 3 / 34

Indexing and Slicing Index with square brackets Negative indexing gets elements from the end of list I lst[-1] is the last element I lst[-2] is the second to last element Can index multiple times with lst_of_lst[][] Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 4 / 34

Builtins len(lst): gives the number of elements sum(lst): adds up elements a in lst: checks presence all(lst)/any(lst): return True is any/all in lst are True max(lst)/min(lst): biggest/smallest element reversed(lst): iterator of elements in reverse order zip(lst1, lst2): list of tuples with one element from each list sorted(lst): returns new sorted list Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 5 / 34

Right Way to Iterate Iterate with for x in lst: I Then use x in the loop Never do for i in range(len(lst)): I Then use lst[i] in the loop Index and value with for i,x in enumerate(lst): I Useful if you sometimes want lst[2*i] or lst2[i] Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 6 / 34

Modifying Lists lst[i] = v: Change an element or slice by assigning to it lst.append(v): Add an element lst.extend(vs): Add an iterable lst.remove(v):remove a specific value del lst[i]: remove a specific index or range lst.insert(i,v): insert before a certain index with lst.pop(i) remove and return index lst.sort(): in place sort Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 7 / 34

Multiplication and Copies Multiplying a list adds it to itself. I The component lists are not copies, they re the same object Shallow copy a list with lst[:] Use the copy module for deep copy I copy.deepcopy(lst) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 8 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 9 / 34

Tuples Immutable lists. Standard notation is (a, b, c, d) I The parentheses aren t necessary though. Support unpacking: x, y, z = t where t is a 3 element tuple Write (x,) for a single element tuple. Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 10 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 11 / 34

Methods s.split(sep): returns a list of substrings separated by sep s.strip(): strips whitespace from ends I Can specify non-whitespace chars to remove: s.strip( abc ) s.isspace(): returns True if all chars in s are whitespace s.lower(): converts all characters to lowercase Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 12 / 34

Join s.join(str_list): Concatenates the strings in str_list with s as a separator. When s is empty string: efficient way to concatenate strings Use space as s to join words with spaces Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 13 / 34

Find and Replace s.find(sub) I finds the starting index of the first occurrence of sub in s s.replace(old,new) I replaces all occurrences of old in s with new Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 14 / 34

Formatting s.format(arg1,arg2): replaces {} in s with args {name!conversion:format} provides options on top of {} Use {0}{1}... to refer to positional arguments Use {name} and then s.format(name=arg) for named args {!s} {!r} {!a} call str()repr()and ascii() before substitution {:4}{:7} at least x number of chars {:b}{:x}... formats number as binary, hex... Lots of other stuff in Format Specification Mini-Language Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 15 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 16 / 34

Basics A dictionary is a hash map I It hashes the keys to lookup values I Keys must be immutable so that the hash doesn t change dict() and {} are empty dictionaries dict([(k1, v1), (k2, v2)]) or {k1:v1, k2:v2} dict(zip(key_lst, val_lst)) d[k] accesses the value mapped to k d[k] = v updates the value mapped to k Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 17 / 34

Methods len(), in, and del work like lists d.keys() and d.values() return views of the keys and values. I Views support iteration, len(), and in I Views change when the dictionary changes d.items() is a view of (k,v) pairs d.get(k,x) looks up the value of k. Returns x if k not in d d.setdefault(k,x) same as d.get(k,x) I Also sets d[k] = x if k not in d d.pop(k,x) Return and remove value at k. Returns x as default Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 18 / 34

Switch Statement Python doesn t have a switch(x) Dictionaries do the job Replace long if x = a: elif x = b: elif... I With a dictionary lookup Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 19 / 34

Defaultdict from collections import defaultdict dd = defaultdict(f) if k not in dd then x = dd[k] I dd[k] = f() I x = dd[k] Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 20 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 21 / 34

Basics No order, no duplicates Hash Set: elements must be immutable Empty set: set() not {} (empty dict) {1, blah, 5, -1} Can de-duplicate a list: list(set(lst)) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 22 / 34

Methods s.add(v): adds a value to set s.remove(v): removes v. will raise an error if v not in s s.discard(v): removes v. will not raise error s.difference(s2) -> s - s2: elements in s but not s2 s.union(s2) -> s s2: elements in s or s2 s.intersection(s2) -> s & s2: elements in s and s2 s.update(s2): s = s s2 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 23 / 34

Frozen Sets frozenset({x, y, z}) Immutable version of set Can be used as dictionary keys and elements of other frozensets Same operations as sets except any that mutate (add, update) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 24 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 25 / 34

List Comprehensions [expr for v in iter] [expr for v1,v2 in iter] [expr for v in iter if cond] Translation: res = [v1 * v2 for v1, v2 in lst if v1 > v2] res = [] for v1, v2 in lst: if v1 > v2: res.append(v1 * v2) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 26 / 34

Nested List Comp [[x for x in lst1] for lst1 in lst2] Translation: res = [] for lst1 in lst2: inter = [] for x in lst1: inter.append(x) res.append(inter) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 27 / 34

Extra for s and if s [x for x in lst1 if x > 2 for y in lst2 for z in lst3 if x + y + z > 8] Translation: res = [] for x in lst1: if x > 2: for y in lst2: for z in lst3: if x + y + z > 8: res.append(x) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 28 / 34

Outline 1 Data Types Lists Tuples Strings Dictionaries Sets 2 Comprehensions Lists Other Comprehensions 3 Extras Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 29 / 34

Dictionary Comprehensions Like lists but swap [] for {} Starts with: d = dict() Appends with: d[k] = v {k: v for k,v in lst} Translation: d = dict() for k, v in lst: d[k] = v Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 30 / 34

Set Comprehensions Like dictionaries but no : Starts with: s = set() Appends with: s.add(v) {x for x in lst} Translation: s = set() for x in lst: s.add(x) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 31 / 34

Tuple Comprehensions? tup = (x for x in lst) type(tup) <class generator > We ll cover generators later Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 32 / 34

Tricks x if cond else y x, y, z = a, b, c x, y, z = abc x, *rest, y, z = range(6) y <= x <= z (1,) Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 33 / 34

Python Docs docs.python.org Library Reference I Everything that s builtin including modules (math, collections,...) Language Reference I What happens when I assign a variable, or import something Tutorial/HOWTOs/FAQs Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 34 / 34