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

Similar documents
Data Structures. Lists, Tuples, Sets, Dictionaries

Python Intro GIS Week 1. Jake K. Carr

Introduction to Python! Lecture 2

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

The Practice of Computing Using PYTHON

Programming in Python

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

Collections. Lists, Tuples, Sets, Dictionaries

LECTURE 3 Python Basics Part 2

Python Tutorial. CSE 3461: Computer Networking

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

Python Evaluation Rules

Notebook. March 30, 2019

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

CS Summer 2013

Python: common syntax

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

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

John Perry. Fall 2009

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

Topic 7: Lists, Dictionaries and Strings

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Slicing. Open pizza_slicer.py

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

Python Review IPRE

Collections. John Perry. Fall 2011

University of Texas at Arlington, TX, USA

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

Python for Non-programmers

Lecture 7: Python s Built-in. in Types and Basic Statements

Programming to Python

Genome 373: Intro to Python II. Doug Fowler

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

MUTABLE LISTS AND DICTIONARIES 4

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Intro. Scheme Basics. scm> 5 5. scm>

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Ceng 111 Fall 2015 Week 8a

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

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

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

Python Review IPRE

Numbers, lists and tuples. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Programming Fundamentals and Python

Python Programming: Lecture 2 Data Types

ENGR 102 Engineering Lab I - Computation

ENGR 101 Engineering Design Workshop

Lists How lists are like strings

Introduction to Python

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

Python: Short Overview and Recap

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

CIS192 Python Programming

CMSC201 Computer Science I for Majors

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

Python - Variable Types. John R. Woodward

Using Scala in CS241

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

Recall that strings and tuples are immutable datatypes, while lists are mutable datatypes. What does this mean?

Iterators & Generators

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Script language: Python Data structures

MITOCW watch?v=rvrkt-jxvko

MEIN 50010: Python Data Structures

CMSC201 Computer Science I for Majors

Lists, loops and decisions

Advanced Python. Executive Summary, Session 1

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

CS 234 Python Review Part 2

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

Introduction to Python

The Dynamic Typing Interlude

Part III Appendices 165

CMSC201 Computer Science I for Majors

Python and Bioinformatics. Pierre Parutto

6. Data Types and Dynamic Typing (Cont.)

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

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Comp 151. More on working with Data

Sequences and iteration in Python

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Overview of List Syntax

Problem Solving for Intro to Computer Science

Types, lists & functions

Here n is a variable name. The value of that variable is 176.

1 Strings (Review) CS151: Problem Solving and Programming

Some material adapted from Upenn cmpe391 slides and other sources

CS1 Lecture 12 Feb. 11, 2019

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

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Beyond Blocks: Python Session #1

Episode 3 Lists and Strings

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

IT441. Network Services Administration. Data Structures: Lists

All programs can be represented in terms of sequence, selection and iteration.

CS1 Lecture 3 Jan. 22, 2018

Introduction to Python (All the Basic Stuff)

Transcription:

CS2304: Sequences and Collections

Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for item in mylist:). Python has 5 built-in sequence types. In this set of slides we ll talk about: The str, tuple, and list sequences/collections. There are also bytearray and bytes sequence types. We may discuss these later in the semester.

First Some Review: Strings A collection of characters ex. Hello World. Single and double quotes are pretty much interchangeable: So Hello World is the same as Hello World. While or are acceptable, they do need to match so won t work. Remember can be used for multi-line comments. Strings in Python are for the most part very flexible. + Will concatenate two or more strings. * Can be used as well, ex. hello *3.

Review: String Basics Strings can use bracket notation like arrays/ strings in other languages. >>> s = Hello World >>> s[0] H >>> s[3] l Oddly, at least coming from another language, you can also use negative indices. You start at the end of the string and count backwards: >>> s[-1] d

Review: String Slicing String slicing is supported, giving you substrings: >>> s = Hello World >>> s[0:3] Hel >>> s[3:6] lo Strings are immutable, so trying to modify an individual cell will cause an error: >>> s[0] = L # TypeError You can always create another string though.

Review: Iterating Through Strings Recall: We can use a for loop to move through a string. for x in s: print(x) The loop will iterate through the characters, printing them one by one: H e l

Our Next Sequence: Tuples You can think of a tuple as being kind of a like a C struct. Or like a Java class with only data items and without member functions. You can group several different types together into a collection. So, you can have a tuple with a string, a number, and a boolean value. Or tuple made up of lists and other tuples. Each item in the tuple is an object reference. Tuples are built-in into Python and can be created without formally defining a new data type. Tuples, like strings, are also immutable.

Creating And Using Tuples To create a tuple you just list values separated by commas: >>> t = hello, 1, True Parentheses are often used but not required: >>> t = ( hello, 1, True) You can return tuples: # at the end of a function return ( hello, 1, True) # elsewhere t = func() You can also capture the individual values: x, y, z = func()

Tuples: Accessing The Items Like strings, you can use bracket notation: >>> t = ( Hello, 1, True) >>> t[0] Hello >>> t[2] True Negative indexes work too, you count from the back or end of the tuple: >>> t[-1] True

Tuple Slicing Slicing is supported, giving you sub-tuples: >>> t = ( hello, 1, True) >>> t[0:1] ('hello',) >>> t[1:3] (1, True) Like strings, tuples are immutable, so trying to modify an individual item will cause an error: >>> t[0] = L # TypeError You can always create another tuple though: >>> t = t[0:1] # Works fine

Iterating Through Tuples These work just like they did with strings: for x in t: print(x) The loop will iterate through the items, printing them one by one: hello 1 True

Other Useful Tuple Information Tuples support a few useful functions: t.count(x) - gives you the number times x occurs in the tuple. t.index(x) - gives you the index of the left most occurrence of x. >>> t = ( hello, 1, True) >>> t.count( hello ) 1 >>> t.index(true) 1 # because 1 counts as true >>> t = ( hello, 0, True) >>> t.index(true) 2

More (Hopefully) Useful Information You can use the + operator with tuples as well: >>> t = ( hello, 1, True) >>> f = t[0:1] + ( balloons,) + t[1:3] >>> f ('hello', 'balloons', 0, True) Of course, this is actually creating another tuple. The membership operator works with tuples: >>> if hello in t:... print( We found it. ) We found it. >>> if world in t:... print( We found it. ) >>>

Passing Tuples To Functions There are a few ways to pass tuples to functions, one is fairly straightforward: >>> t = ( hello, 1, True) >>> func(t) # elsewhere def func(var): # break apart the tuple here msg = var[0]+ str(var[1]) # use the pieces of the tuple

Passing Tuples To Functions You can also expand the tuple automatically using the *: # note this function has 3 parameters def func2(x, y, z): # do something x, y, and z pass # call the function using the tuple # remember the tuple has 3 elements >>> func2(*t) Trying this with the tuple f(which has 4 items) will result in an error.

Now We Move On To Lists A list is an ordered sequence of zero or more object references. Very flexible, if performance isn t crucial lists will often take the place of what we traditionally think of as an arrays job. There is an array type we will examine later. Since each item is an object reference, elements don t have to be the same type. Lists, like tuples, are built-in into Python and can be created very easily. Lists are mutable, unlike like strings and tuples.

Basic List Usage We ve seen this in class before, but this creates an empty list: >>> l = [] We ve also seen examples like this in projects: >>> rates = [.10,.15,.25] You can have different data types in the same list as well as nested lists: >>> l = [ hello, 1, True, [.10,.15,.25]]

List Slicing CS2304: Python for Java Programmers Slicing is supported, giving you sub-lists: >>> l = [ hello, 1, True, [.10,.15,.25]] >>> l[0:3] ['hello', 1, True] >>> l[2:4] [True, [0.1, 0.15, 0.25]] Lists are mutable, so trying to modify an individual cell works as you would expect: >>> l[0] = L # Works fine >>> l[2] = W # Also works fine >>> l ['L', 1, 'W', [0.1, 0.15, 0.25]]

Iterating Through Lists Recall: We can use a for loop to move through a list. for x in l: print(x) The loop will iterate through the items, printing them one by one: L 1 W

List Functions Like tuples, lists support count and index: l.count(x) - gives you the number times x occurs in the list. l.index(x) - gives you the index of the left most occurrence of x. >>> l = [ hello, 1, True] >>> l.count( hello ) 1 >>> l.index(true) 1 # because 1 counts as true >>> l = [ hello, 0, True] >>> l.index(true) 2

More List Functions Lists support far more functions than just count and index. l.append(x) - appends item x at the end of l. l.insert(i, x) - inserts item x at index i. l.pop() - removes the right most value in l. l.remove(x) - removes the left most occurrence of x. l.reverse() - reverses the order of l in-place. Take a look at the book or resources online for more functions.

More (Hopefully) Useful Information You can use the + operator with lists as well: >>> l = [] >>> l += [1, hello ] >>> l += [[1, 2, 3]] >>> l [1, 'hello', [1, 2, 3]] The membership operator works with lists: >>> if hello in l:... print( We found it. ) We found it. >>> if world in l:... print( We found it. ) >>>

List Comprehensions Let s say you d like to quickly create a list filed with data, you could do something like this: l = [] for x in range(10): l.append(x**2) >>> l [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] This accomplishes the same thing: l =[x**2 for x in range(10)]

More List Comprehensions You can do far more interesting things with list comprehensions: [(x, y) for x in [1,2,3] for y in [3,1,4] if x!= y] This (more complex code) accomplishes the same thing: l = [] for x in [1, 2, 3]: for y in [3, 1, 4]: if x!= y: l.append((x,y)) >>> l [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Other Uses For List Comprehensions As filters: l = [-1, -2, 0, 2, 4] pos = [x for x in l if x >=0] >>> pos [0, 2, 4] They also work with functions, and types other than numbers: >>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']

One More Collection: Dictionaries The types we ve looked at are groupings of values that you could access via l[0] or t[0]. Regardless of type, an index (a number) is a common way to access the collections we ve seen so far. Python also has a mapping or associative array type called a dictionary. Instead of being indexed by numbers, a dictionary is indexed using keys. So a dictionary is made up of (unordered) key & value pairs. A key can be any immutable type, so strings, numbers, and tuples (if they don t contain any mutable objects).

Creating And Using Dictionaries To create an empty dictionary you use curly brackets or braces: >>> m = {} To create dictionary a with some starting values: >>> m = { hello :1, world :2} You can then use m kind of like an array: >>> m[ hello ] 1 You can add new items using the same method: m[ foobar ] = 3

Dictionaries: Other Useful Functions If you want to test whether something is the dictionary you can use get: # j is not a key in the map, get will # return None if doesn t find the key >>> m.get( j ) is None True >>> m.get( hello ) is not None True There are functions to get the keys and the values: >>> list(m.keys()) >>> list(m.values())

Iterating Through Dictionaries You can use for loops to iterate through all of the key, value pairs for k, v in m.items(): print(k, v) hello 1 world 2 foobar 3 If you want to delete a individual piece of the dictionary: del m[ hello ]