Collections. Lists, Tuples, Sets, Dictionaries

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

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

The Practice of Computing Using PYTHON

Advanced Algorithms and Computational Models (module A)

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

Homework notes. Homework 2 grades posted on canvas. Homework 3 due tomorrow. Homework 4 posted on canvas. Due Tuesday, Oct. 3

Python Review IPRE

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

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

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

Python: common syntax

MUTABLE LISTS AND DICTIONARIES 4

Chapter 8 SETS AND DICTIONARIES

University of Texas at Arlington, TX, USA

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

LECTURE 3 Python Basics Part 2

Introduction to Python

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Programming in Python

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Python for Non-programmers

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

Lists, Tuples and Dictionaries. HORT Lecture 10 Instructor: Kranthi Varala

CS Summer 2013

Sequences and iteration in Python

Python Intro GIS Week 1. Jake K. Carr

Python and Bioinformatics. Pierre Parutto

ENGR 102 Engineering Lab I - Computation

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Comp 151. More on working with Data

Python Review IPRE

CS1 Lecture 11 Feb. 9, 2018

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

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

Python. Karin Lagesen.

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

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

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

Python debugging and beautification

Introduction to Problem Solving and Programming in Python.

Try and Error. Python debugging and beautification

Notebook. March 30, 2019

MEIN 50010: Python Data Structures

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

Python - Variable Types. John R. Woodward

Introduction to Python! Lecture 2

python 01 September 16, 2016

Collections. John Perry. Fall 2011

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

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

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Python Tutorial. Day 1

Ch.2: Loops and lists

Part III Appendices 165

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

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

CS 234 Python Review Part 2

CIS192: Python Programming

ENGR/CS 101 CS Session Lecture 12

COMP 204: Dictionaries Recap & Sets

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

Topic 7: Lists, Dictionaries and Strings

TUPLES AND RECURSIVE LISTS 5

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

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

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

STSCI Python Introduction. Class URL

Introduction to Python

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

Do not turn this page until you have received the signal to start.

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

The Big Python Guide

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Compound Data Types 1

John Perry. Fall 2009

Here is a simple dictionary in Python. Let s store the telephone dialing codes for a few countries.

Teaching London Computing

COMP 204: Sets, Commenting & Exceptions

CSC Software I: Utilities and Internals. Programming in Python

Chapter 2: Lists, Arrays and Dictionaries

An Introduction to Python

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

The current topic: Python. Announcements. Python. Python

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Ch.2: Loops and lists

CIS192 Python Programming

Advanced Python. Executive Summary, Session 1

Slicing. Open pizza_slicer.py

Lists How lists are like strings

CS1 Lecture 12 Feb. 11, 2019

The Dynamic Typing Interlude

Python Lists, Tuples, Dictionaries, and Loops

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

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

Compound Data Types 2

Data Handing in Python

Transcription:

Collections Lists, Tuples, Sets, Dictionaries

Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again Homework 2 due tomorrow Homework 3 is posted on canvas

Some notes about functions Remember, a function is usually supposed to use its inputs The function ask_yes_or_no(prompt) is supposed to use prompt Functions are defined outside of other functions They are only called inside other functions! This is that whole division of labor business Splitting your code into functions makes it easy to read/write It can also save you lots of copy/paste if you have to do something over and over again

Collections We ve looked at simple variable types like int, float, and boolean However, often we want to work with a collection of values (customers, books, students) Python supplies four kinds of collections: lists, tuples, sets, and dictionaries Collections, like simple values, can be stored in variables There are two basic approaches to working with a collection: 1. You can select specific individual elements from the collection and work with them individually 2. You can work with the collection as a whole, producing a new collection

Lists A collection of zero or more elements Example: my_list = ["one", "two", "three"] Not necessary to have the same type (not so in Java!) To access a single element in a list, give the list, then in brackets give the index of the desired element, starting from zero my_list[0] is "one", my_list[1] is "two", and my_list[2] is "three You can also use negative indices (not true in Java!) my_list[-1] is "three", my_list[-2] is "two", and my_list[-3] is "one Stick to positive indices unless you have a good reason not to! It is an error to index my_list with an integer outside the range -3 to 2 Lists are mutable: You can change their contents my_list[2] = "many

List elements Elements need not be simple values: can be other lists, sets Lists can be multidimensional as well Example: names = [["Mary", "Jane", "Sally", "Ann"], ["Tom", "Dick", "Harry"]] Lists of lists accessed with double indexing Example: names[0] is ["Mary", "Jane", "Sally", "Ann"] names[0][1] is Jane

Functions vs. Methods An object consists of some data (describing the state of the object) and some operations on that data (which may change the state of the object) Lists, sets, tuples, and dictionaries are kinds of objects Will see more about objects later A function is an operation that is not part of an object A function may take objects as arguments, or produce them as results, but it isn't part of those objects Syntax: function_name(arg,..., arg) Example: len(my_list) returns the number of elements in my_list A method is an operation that belongs to an object Syntax: object.method_name(arg,..., arg) Example: my_list.sort() sorts my_list

List functions and methods Functions print(my_list) #prints all elements in the list len(my_list) #returns the length of the list Some functions only work if a list is homogenous (e.g., max(my_list), min(my_list)) Homogenous means of the same type (e.g., int, float) Methods my_list.append(x) #adds x to the end of the list Be careful: append returns None my_list.count(x) #returns the number of times x appears in the list

Looping through a list range(start, end) generates a series of integers starting with start and going up to, but not including, end range is often used to generate a sequence of list indices A range isn't a list, but it can be turned into a list by using it as an argument to the list function A for loop has the syntax for variable in range(start, end): statements Can also do for variable in list: statements IDLE examples: lists.py, list_examples.py

Slicing You can get a slice of a list using the syntax list[from:upto] This creates a new list containing the elements starting at from and going up to (but not including) upto Example: list = [0, 1, 2, 3] list[1:3] =? list[1:3] is [1,2] list[:2] is [0,1]

Indexing into strings A string isn't a list, but it can be indexed like one Example: "Computer"[0] is 'C "Computer"[3:6] is 'put Strings, unlike lists, are immutable they cannot be modified comp = "Computer comp[3:6] = "get" Traceback (most recent call last): File "", line 1, in comp[3:6] = "get" TypeError: 'str' object does not support item assignment However, a variable containing a string can be assigned a different value comp = comp[:3] + "get" + comp[6:] comp is 'Comgeter'

Sets A set is an unordered collection of values, containing no duplicates Because it is unordered, you cannot index into a set Because it contains no duplicates, any value is either in the set once, or it isn t in the set Similar to lists, values can be different types A set is written as a comma-separated list of values, enclosed in braces Example: {1, 3.6, 'a', True} You can t write an empty set (a set with no elements) as {}, because that s a dictionary you have to write it as set() Since you can t index into a set, you have to use the simpler kind of for loop to process each and every element for elem in set: do something with elem

Sets methods You can add and remove items item in set Return True if set contains item, else False item not in set Equivalent to not item in set. Not too many other useful methods After all, main purpose of a set is to store unique values

Dictionary A dictionary maps a key to a value keys are immutable Syntax: dict = { key1 : value1,..., key_n : value_n } Example: num_to_str = {"two :2, "three :3, "four :4, "five :5} You can index into a dictionary like you would a list, but the indices are keys, not necessarily integers Example: num_to_str[ three ] is 3

Dictionary methods Dictionaries have methods that can be explored in IDLE, but also some with unusual syntax d[key] Return the item of d with key key. Raises a KeyError if key is not in the map d[key] = value Set d[key] to value. del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map. key in d Return True if d has a key key, else False key not in d Equivalent to not key in d.

Tuples A tuple is a way to collect a small number of related values into a single value, for convenience in handling Syntax: (value_1,..., value_n) Example: fun_book =("The Princess Bride", "William Goldman", 1973) Example: The function divmod(int_1, int_2) returns a tuple containing the quotient and the remainder when int_1 is divided by int_2 IDLE example: divmodgcd.py Tuples are immutable You can index into a tuple to retrieve values, but you can t change any of its values

Working with Tuples In Python, you can say: a, b, c = 3, 5, 7 This sets a to 3, b to 5, and c to 7 It s the same as (a, b, c) = (3, 5, 7) This is usually the easiest way to get information out of a tuple Example: fun_book =("The Princess Bride", "William Goldman", 1973) (title, author, date) = fun_book

What are all these for? Lists, like ["John", "Mary", "Bill", "Mary"], are the most heavily used kind of collections in Python, and should be the first thing to consider Sets, like { John", "Mary", "Bill"}, are just the ticket when you need to keep track of what s in and what s out Dictionaries, like {"John": 5551212, "Mary": 5551234}, are obviously for looking things up Tuples, like ("CIT 590", Rado"), are a convenient way of bundling related pieces of information together All this becomes a lot more obvious with experience!

Summary: four types of collections List Ordered Mutable Tuple Ordered Immutable Set Not ordered No duplicates Dictionary Associates one value with another