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

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

Python Intro GIS Week 1. Jake K. Carr

Advanced Python. Executive Summary, Session 1

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

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

COMP1730/COMP6730 Programming for Scientists. Strings

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

The Practice of Computing Using PYTHON

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

University of Texas at Arlington, TX, USA

Python. Executive Summary

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

Programming in Python

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

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

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

Programming in Python 3

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

Data Structures. Lists, Tuples, Sets, Dictionaries

Types, lists & functions

Python: common syntax

18.1. CS 102 Unit 18. Python. Mark Redekopp

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

Lists How lists are like strings

egrapher Language Reference Manual

Lists, loops and decisions

Compound Data Types 1

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Python Review IPRE

MEIN 50010: Python Flow Control

UNIT-III. All expressions involving relational and logical operators will evaluate to either true or false

Introduction to Python! Lecture 2

Jarek Szlichta

Introduction to Mathematical and Scientific Programming TUTORIAL WEEK 2 (MATH 1MP3) Winter 2019

Python and Bioinformatics. Pierre Parutto

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

Beyond Blocks: Python Session #1

COLLEGE OF ENGINEERING, NASHIK-4

Variable and Data Type I

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

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

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Introduction to Python

Brush up Python. December 20, 2018

Ch.2: Loops and lists

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Introduction to Python

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

MULTIPLE CHOICE. Chapter Seven

MUTABLE LISTS AND DICTIONARIES 4

Sequences and iteration in Python

Variable and Data Type I

Comp 150 Exam 2 Overview.

ENGR 101 Engineering Design Workshop

Control Structures 1 / 17

UNIVERSITÀ DI PADOVA. < 2014 March >

CMSC201 Computer Science I for Majors

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Introduction to programming using Python

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

Babu Madhav Institute of Information Technology, UTU 2015

CSCE 110 Programming I

CS1 Lecture 11 Feb. 9, 2018

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

CIS192 Python Programming

Iterators & Generators

A Brief Introduction to Python

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

CIS192 Python Programming

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

1 Strings (Review) CS151: Problem Solving and Programming

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Flow Control: Branches and loops

Exercise: The basics - variables and types

Chapter 10: Creating and Modifying Text Lists Modules

CMSC201 Computer Science I for Majors

Fundamentals of Programming (Python) Getting Started with Programming

Introduction to Problem Solving and Programming in Python.

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

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

Collections. Lists, Tuples, Sets, Dictionaries

Visualize ComplexCities

Introduction to Python

Strings. Genome 373 Genomic Informatics Elhanan Borenstein

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

GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING Question Bank

Scripting Languages. Python basics

Python 1: Intro! Max Dougherty Andrew Schmitt

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

VLC : Language Reference Manual

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review

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

CIS192 Python Programming

OOP and Scripting in Python Advanced Features

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Python Review IPRE

Transcription:

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

Indexing Python Sequence Types Each element in a sequence can be extracted by using indexing syntax seqtype[<integer>] First element has index 0 >>> mystr = 'hello str' >>> a = mystr[0] >>> print(a) h

Indexes can be thought of as positions rather than elements Makes slicing syntax more intuitive Python Indexing h e l l ho s t r 0 1 2 3 4 5 6 7 8 9-9 -8-7 -6-5 -4-3 -2-1

Sequence Types: list and tuple Python Sequence Types While str only contains a sequence of characters list and tuple are containers for any type or collection of types list literal enclosed in [ ] Elements separated by commas tuple literal usually enclosed in ( ) Elements separated by commas Parenthesis mandatory for empty tuple >>> mytuple = ('string', 83, 1+4j) >>> print(type(mytuple)) <class 'tuple'> >>> mylist = ['lststring', 12.22, b'\xaf'] >>> print(type(mylist)) <class 'list'>

Sequence Types: list and tuple Support the same indexing operations as str and bytes Python Sequence Types >>> print(mytuple[2]) (1+4j) >>> print(mylist[0]) lststring

Slicing Python Sequence Types Allows us to obtain a subset of the sequence seqtype[start:stop:step] Omitted indexes take default values start: 0 stop: <last index> step: 1

Slicing Examples mylst = [1,12,3.3,8,'a',67,33,'c',9] >>> print(mylst[1:4]) [12, 3.3, 8] >>> print(mylst[1:]) [12, 3.3, 8, 'a', 67, 33, 'c', 9] >>> print(mylst[:7]) [1, 12, 3.3, 8, 'a', 67, 33] >>> print(mylst[::2]) [1, 3.3, 'a', 33, 9] >>> print(mylst[::-1]) [9, 'c', 33, 67, 'a', 8, 3.3, 12, 1] >>> print(mylst[9]) #out of range index Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range >>> print(mylst[7:12]) #out of range slice ['c', 9] 1 12 3.3 8 'a' h 67 33 'c' 9 0 1 2 3 4 5 6 7 8... Slice always returns a sequence Difference between mylst[0] and mylst[0:1] -2-1 9

Difference between tuple and list list elements can be added, changed or removed after creation tuple cannot be changed once it is created Neither can str Python Sequence Types >>> mytuple[0] = 'new first element' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> mylist[0] = 'new first element' >>> print(mylist) ['new first element', 12.22, b'\xaf'] >>> mystr = 'abcd' >>> mystr[0] = 'x' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment

Some operations on sequence types >>> a = 'hello' # concatenation >>> a = a + 'world' >>> print(a) helloworld Python Sequence Types >>> mylst = ['a','b',123] >>> mylst = mylst + ['newlast'] >>> print(mylst) ['a', 'b', 123, 'newlast'] >>> a = "hello"*4 #repetition >>> print(a) hellohellohellohello >>> a = (1,2,3)*4 >>> print(a) (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

Membership testing Using the in keyword Python Sequence Types >>> mylst = ['word', 12.2, 33] >>> print('wo' in mylst) False >>> print('word' in mylst) True >>> print(33 in mylst) True >>> mystr = 'multiple words' >>> print('lti' in mystr) True

Iterating over sequence types Python Iterators A sequence type is an ordered set of values/objects An iterator returns each value in a sequence one after the other Iterators can be obtained from them using the iter() built-in function which returns an iterator Each value can be returned from an iterator by calling the next() built-in function with an iterator argument

>>> mytuple = (1.22, 2+3j, ['a','b']) >>> tup_it = iter(mytuple) >>> type(tup_it) <class 'tuple_iterator'> Python Iterators >>> print(next(tup_it)) 1.22 >>> print(next(tup_it)) (2+3j) >>> print(next(tup_it)) ['a', 'b'] >>> print(next(tup_it)) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration

Iterating over sequence types Python Iterators Iterators cannot be reset New iterator needs to be created in order to obtain values from the beginning Iterators raise the StopIteration exception to signal to the caller that there are no more values to return

for statement Python loops Executes a suite of statements for each item in an iterator after assigning the item to a loop variable for <var> in <seq-type/iterator>: statement-1 statement-2 Statement-3 Statements 1-3 are executed for each value of <var> from the sequence or iterator

for statement Python loops >>> mynums = (0,1,2,3,4,5,6) >>> for num in mynums:... print('square of', num, 'is', num**2)... square of 0 is 0 square of 1 is 1 square of 2 is 4 square of 3 is 9 square of 4 is 16 square of 5 is 25 square of 6 is 36

for statement range() built-in function can be used to write loops like the one above more concisely Python loops >>> for num in range(7):... print('square of', num, 'is', num**2)... square of 0 is 0 square of 1 is 1 square of 2 is 4 square of 3 is 9 square of 4 is 16 square of 5 is 25 square of 6 is 36 See help(range)

Algorithm: find maximum of n numbers and its position Loops Largest Value Algorithm Let list of numbers be numlist and let x represent the largest integer and p its position 1. Let x = numlist[0] and p = 0 2. Repeat for k = 0 to k = n-1 If numlist[k] > x then x = numlist[k] and p = k

len() is a built-in function that returns the number of items in a sequence object Loops Implementation maxnum = numlist[0] maxpos = 0 for idx in range(len(numlist)): if numlist[idx] > maxnum: maxnum = numlist[idx] maxpos = idx print(maxnum,"at",maxpos)

enumerate() built-in function allows us to implement it in a more pythonic way Loops Implementation maxnum = numlist[0] maxpos = 0 for idx, num in enumerate(numlist): if num > maxnum: maxnum = num maxpos = idx print(maxnum,"at",maxpos)

while statement Loops While loop Executes a suite of statements as long as a condition is true while <expression>: statement-1 statement-2 statement-3 Statements 1-3 are executed repeatedly as long as <expression> evaluates to True

Loops While loop Fibonacci Sequence Is a sequence of integers with the characteristic that each integer is the sum of the two preceding it 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,...

A program to generate the fibonacci numbers less than a value Loops Fibonacci Sequence 1 n = input('enter number:') 2 n = int(n) 3 a, b = 0, 1 4 while b < n: 5 print(b) 6 a, b = b, a+b input() reads a line from stdin and returns a str int() returns an int given a int, float or str argument Tuple as target of assignment called tuple unpacking

Loops Fibonacci Sequence $ python3 fibonacci.py enter number:120 1 1 2 3 5 8 13 21 34 55 89

Loops Break and continue break and continue break will terminate the loop within which it is enclosed and continue will cause the loop to skip to the next iteration

Loops 1 while True: 2 inp = input('enter a word: ') 3 if inp == 'end' or inp == 'End': 4 break 5 elif inp == 'skip' or inp == 'Skip': 6 continue 7 else: 8 print(inp) Break and continue $ python3 break_continue.py Enter a word: test test Enter a word: test with words test with words Enter a word: skip Enter a word: Skip Enter a word: one more one more Enter a word: end $

Python Review Sequence Types str, bytes, tuple, list Indexing With integers or slices Common operations Concatenation (+), repetition (*), membership testing, len() built-in, assigning to a list index Iterators from sequences for statement and range() and enumerate() built-in functions

Methods of Sequence Types Python Methods Many operations on sequence types are defined as methods Methods are functions that are attributes to a variable i.e They are accessed with the dot. operator <object/variable>.method(<args))

Methods str Methods of str Type Close to 50 utility methods defined. We examine a few str methods return a new string Strings cannot be changed once created. Hence cannot be modified in place

upper() Return string with characters in uppercase >>> a = 'this is a sentence' Methods str >>> print(a.upper()) THIS IS A SENTENCE >>> print(a) this is a sentence >>> a = a.upper() >>> print(a) THIS IS A SENTENCE

find() Locate a substring Methods str >>> a = 'this is a sentence' >>> print(a.find('is')) 2

isalpha(), isdigit() Test whether string has only letter or only digits Methods str >>> print('wordwithnospaces'.isalpha()) True >>> print('wordwithnospaces'.isdigit()) False >>> arnum = ' ٥٠٦١' >>> print(arnum.isdigit()) True

Methods All Methods dir() and help() dir() lists all attributes bound to a variable or object help() show detailed documentation See help(str) for a list of all methods and their description

Methods list Methods of list Type list methods that modify the list operate in-place Do not return any result

append() Add an element to the end of the list Methods list >>> mylst = ['3', 3.0, 'string'] >>> mylst.append(['a','b']) >>> print(mylst) ['3', 3.0, 'string', ['a', 'b']]

insert() Insert object before index Methods list >>> mylst = ['3', 3.0, 'string'] >>> mylst.insert(2, ['a','b']) >>> print(mylst) ['3', 3.0, ['a', 'b'], 'string']

reverse() Reverse the list in-place Methods list >>> mylst = ['3', 3.0, 'string'] >>> mylst.reverse() >>> print(mylst) ['string', 3.0, '3']

sort() Sort the list in-place Methods list >>> mylst = ['money', 'apple', 'cat', 'yes'] >>> mylst.sort() >>> print(mylst) ['apple', 'cat', 'money', 'yes']

index() Return index of first occurrence of value in sequence Methods list >>> mylst = ['money', 'apple', 'cat', 'yes', 'cat'] >>> print(mylst.index('cat')) 2 Implement using built-ins

List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]

The previous construct is common So Python provides a shorter syntactic equivalent Example List comprehension >>> n = 12 >>> squares = [i**2 for i in range(n)] >>> print(squares) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121] $ python3 squares.py [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121] Inside square brackets An expression followed by a for clause followed by zero or more for or if clauses