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

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

CS1 Lecture 11 Feb. 9, 2018

MITOCW watch?v=rvrkt-jxvko

Topic 7: Lists, Dictionaries and Strings

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

The Practice of Computing Using PYTHON

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

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

Compound Data Types 1

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

Algorithmic Thinking: Computing with Lists

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

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

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

Data Structures. Lists, Tuples, Sets, Dictionaries

Python Review IPRE

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

Algorithmic Thinking: Computing with Lists

Lists, loops and decisions

Python Intro GIS Week 1. Jake K. Carr

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

Programming in Python

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

Python and Bioinformatics. Pierre Parutto

Python Review IPRE

University of Texas at Arlington, TX, USA

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

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

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

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

MUTABLE LISTS AND DICTIONARIES 4

Compound Data Types 2

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

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

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

Types, lists & functions

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

CMPT 120 Introduction To Computing Science And Programming I. Pseudocode. Summer 2012 Instructor: Hassan Khosravi

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

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

Unit 2. Srinidhi H Asst Professor

Lists. There are several ways to create a new list; the simplest is to enclose the elements in square brackets ( [ and ]):

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

Part III Appendices 165

Episode 3 Lists and Strings

1 Strings (Review) CS151: Problem Solving and Programming

Introduction to Python

Decisions, Decisions. Testing, testing C H A P T E R 7

CS Summer 2013

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

CSC326 Python Sequences i. CSC326 Python Sequences

Introduction to programming using Python

CS1 Lecture 12 Feb. 11, 2019

Functions and Decomposition

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

Advanced Python. Executive Summary, Session 1

Programming Fundamentals and Python

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

Introduction to Python! Lecture 2

Basic Python Revision Notes With help from Nitish Mittal

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

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

CS150 Sample Final. Name: Section: A / B

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

Collections. Lists, Tuples, Sets, Dictionaries

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012

Python for Non-programmers

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

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

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

CIS192 Python Programming

Accelerating Information Technology Innovation

If Statements, For Loops, Functions

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

6.00 Notes On Big-O Notation

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

Python Programming: Lecture 2 Data Types

A Brief Introduction to Python

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

Introduction to Python

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

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Accelerating Information Technology Innovation

Python: common syntax

CS150 - Sample Final

Computational Programming with Python

Algorithm Design and Recursion. Search and Sort Algorithms

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

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

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

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

Overview of List Syntax

Introduction to String Manipulation

1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line

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

EE 355 Unit 17. Python. Mark Redekopp

An Introduction to Python

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food

Transcription:

CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi

All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want to store a collection of values in your programs. a list of values that have been entered by the user or a collection of values that are needed to draw a graph. In Python, lists can be used to store a collection of values. Python can hold values of any type; they are written as a commaseparated list enclosed in square brackets: numlist = [23, 10, -100, 2] words = [ zero, one, two ] junk = [0, 1, two, [1,1,1], 4.0] 1.2

To get a particular value out of a list, it can be subscripted testlist = [0, 10, 20, 30, 40, 50] print testlist[2] 20 print testlist[0] 0 print testlist[10] IndexError: list index out of range Like strings, the first element in a list is element 0 1.3

You can determine the length of a list with the len function: print len(testlist) 6 for i in range(len(testlist)): print testlist[i], 0 10 20 30 40 50 1.4

Lists can be joined (concatenated) with the + operator: testlist + [60, 70, 80] [0, 10, 20, 30, 40, 50, 60, 70, 80] [ one, two, three ] + [1, 2, 3] [ one, two, three, 1, 2, 3] It is also possible to delete an element from a list colours = [ red, yellow, blue ] del colours[1] print colours [ red, blue ] del colours[1] print colours [ red ] 1.5

You can also add a new element to the end of a list with the append colours = [ red, yellow, blue ] colours.append( orange ) colours.append( green ) print colours [ red, yellow, blue, orange, green ] In order to do something similar with a string, a new string must be built with the + operator: letters = abc letters = letters + d letters = letters + e print letters abcde 1.6

print "Enter some numbers, 0 to stop:" numbers = [] x=1 while x!=0: x = int(raw_input()) if x!=0: numbers.append(x) print "The numbers you entered are:" print numbers 1.7

Lists and for loops range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(1,17,3) [1, 4, 7, 10, 13, 16] Range(13,1,2) [] Range(13,1,-2) [13, 11, 9, 7, 5, 3] for i in range(10): # do something with I For loop in Python can iterate over any list not just those produced by the range function. 1.8

There, the for loop iterates over each element in the list words. words = ["up", "down", "green", "cabbage"] for word in words: print "Here s a word: " + word Here s a word: up Here s a word: down Here s a word: green Here s a word: cabbage 1.9

Slicing and Dicing colours = [ red, yellow, blue ] colours[1] = green # set an element with indexing Print colours[1] green print colours[2] # index to retrieve an element blue colours = [ red, yellow, green, blue ] print colours[1:3] [ yellow, green ] In general, the slice [a:b] extracts elements a to b-1 Same as range 1.10

Special Slice Positions Negative values count from the end of a list. -1 refers to the last item in the list -2 to the second-last, and so on colours = [ red, yellow, green, blue ] print colours[0:-1] [ red, yellow, green ] If you leave out one of the values in the slice, it will default to the start or end of the list. [:num] refers to elements 0 to num-1. [2:] gives elements from 2 to the end of the list. 1.11

Examples colours = [ red, yellow, green, blue, orange ] print colours[2:] [ green, blue, orange ] print colours[:3] [ red, yellow, green ] print colours[:-1] [ red, yellow, green, blue ] e [:-1] will always give you everything except the last element; [1:] will give everything but the first element. 1.12

Examples Fibonacci Store the first 20 values in the Fibonacci series in a list such that the index i of the list stores the ith element. Fibonacci series are the numbers in the following integer sequence: 0,1,1,2,3,5, F n = F n-1 + F n-2 F 0 = 0, F 1 =1 1.13

Example Fibonacci fib = [] fib.append('garbage') fib.append(0) fib.append(1) for i in range(3,20): new = fib[i-1] + fib[i-2] fib.append(new) print fib 1.14

Example Fibonacci Store the first 20 values in the Fibonacci series in a list such that the index i of the list stores the ith element. Fibonacci series are the numbers in the following integer sequence: 0,1,1,2,3,5, F n = F n-1 + F n-2 F 0 = 0, F 1 =1 For the odd elements of the series calculate their average For even elements of the series calcuate their sum 1.15

Example Fibonacci def average(list): length = len(list) j=0 sum=0 for i in range(1,length,2): j=j+1 sum = sum+list[i] print list[i] average = float(sum)/j return average def sumforfib(list): length = len(list) sum=0 for i in range(length,2): sum = sum+list[i] print list[i] return sum 1.16

Example Duplicate Store a list of 10 words and determine whether any word has been entered more than once. words= [] for i in range(10): words.append( raw_input("enter word please: ")) flag = False for i in range(10): for j in range(i+1,10): if words[i] == words[j]: print "duplicated" flag = True if flag == False: print "No duplicates" 1.17

Words containing s Store a list of 10 words and determine whether each contains the letter s or not. words= [] for i in range(10): words.append( raw_input("enter word please: ")) for w in words: flag = False for let in w: if let == 's': print w, "contains s" flag = True if flag == False: print w, "does not contain s" 1.18

Store a list of 10 words and determine whether each contains the letter s or not. Remove all occurrences of letter s from all words words= [] for i in range(4): words.append( raw_input("enter word please: ")) length = len(words) for i in range(length): temp = "" for let in words[i]: if let!= 's': temp = temp + let words[i]= temp print words 1.19

Manipulating Slices You can actually do almost anything with list slices colours = [ red, yellow, green, blue ] colours[1:3] = [ yellowish, greenish ] print colours [ red, yellowish, greenish, blue ] colours[1:3] = [ pink, purple, ecru ] print colours [ red, pink, purple, ecru, blue ] we assigned a list of three elements to a slice of length two The list expands to make room or the new elements [ yellowish, greenish] is replaced with [ pink, purple, ecru ]. 1.20

Manipulating Slices If the list assigned is shorter than the slice, the list would shrink colours = ['red', 'yellow', 'green', 'blue'] colours[1:3] = "red" print colours ['red', 'r', 'e', 'd', 'blue'] colours = ['red', 'yellow', 'green', 'blue'] colours[1:3] = ['red'] print colours ['red', 'red', 'blue'] 1.21

Deleting Slices You can also remove any slice from a list: colours = [ red, yellow, green, blue ] del colours[1:3] print colours [ red, blue ] 1.22

Strings Strings are a sequence of characters; lists are a sequence of any combination of types. Any type that represents a collection of values can be used as the list in a for loop. Since a string represents a sequence of characters, it can be used. for char in "abc": print "A character:", char A character: a A character: b A character: c 1.23

Slicing Strings Slices in strings are read only sentence = "Look, I m a string! print sentence[:5] Look print sentence[6:11] I m a print sentence[-7:] string! 1.24

But, you can t modify a string slice sentence = "Look, I m a string! sentence[:5] = "Wow" TypeError: object doesn t support slice assignment del sentence[6:10] TypeError: object doesn t support slice assignment 1.25

Mutability dots = dots + "." # statement #1 The right side of = is evaluated and put into dots. The old value of dots is lost in the assignment values = values + [n] # statement #2 Same with this method of modifying lists values.append(n) # statement #3 The output of this statement is the same as statement 2. Statement 3 requires a lot less work. The whole list in not rebuilt. Data structures that can be changed in-place like lists are called mutable. Strings and numbers are not mutable: they are immutable. Objects depends how they are written, but they have the capability to be mutable 1.26

References There are several cases where the contents of one variable are copied to another. # x copied into y: y = x You probably don t think of copying the contents of a variable as a difficult operation, but consider the case where x is a list with millions of elements. Python avoids making copies where possible To understand this, we need to understand references. 1.27

Every variable in Python is actually a reference to the place in memory where its contents are stored. Conceptually, you should think of a variable referencing its contents like an arrow pointing to the contents in memory. 1.28

When you use a variable in an expression, Python follows the reference to find its contents. Usually, the expression on the right side of an assignment creates a new object in memory. Total = a+b calculates a+b, stores this in memory, and sets total to reference that value. The exception to this is when the right side of an assignment is simply a variable reference (like total=a). In this case, the result is already in memory and the variable can just reference the existing contents 1.29

Aliases When two variables refer to the same contents, they are aliases of each other. it s generally good since it doesn t require copying the contents to another location in memory. When you assign to a variable, you are changing it so the variable now references different contents. (The old contents are thrown away since they are no longer being referenced.) 1.30

Mutable data structures and aliases Mutable data structures (lists and some objects), aliases complicate things. Mutable data structures can be changed without totally rebuilding them, we can change the contents without moving the reference to a new object in memory It s possible to change a variable, and the changes will affect any other variables that reference the same contents. my_list and list_copy are aliases of the same contents. When either one is changed, both are affected. I 1.31

Any expression (that s more complicated than a variable reference) will result in a new reference being created. If this is assigned to a variable, then there is no aliasing. 1.32

Really Copying If you want to make a copy of a variable that isn t a reference, it s necessary to force Python to actually copy its contents to a new place in memory. This is called cloning. Cloning is more expensive than aliasing, There are three methods for this The slice operator can be used to create a clone. You could also make a copy of a list with the list function that creates a new list (out of the old one). So, list(my_list) would give the same result as my_list[:]. the copy module contains a copy function. This function will take any Python object and clone its contents import copy new_obj = copy.copy(obj) 1.33