Programming in Python

Size: px
Start display at page:

Download "Programming in Python"

Transcription

1 3. Sequences: Strings, Tuples, Lists

2 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python interpreter. # # "Real" programs are usually more complicated and thus # need to be commented sometimes. # # Thus, I should say how comments are written in Python: # Everything that follows a hash mark (#) and is not part # of a string is a comment, up to the end of the line. print "Hello, world" # Thus, this is the famous # "hello world" program.

3 Sequences In this lesson, we deal with Python s sequence types: Strings: str and unicode (Immutable) tuples: tuple (Mutable) lists: list Moreover, we get to know for loops.

4 Sequence Example >>> first name = "John" >>> last name = Gambolputty >>> name = first name + " " + last name >>> print name John Gambolputty >>> print name.split() [ John, Gambolputty ] >>> primes = [2, 3, 5, 7] >>> print primes[1], sum(primes) 3 17 >>> squares = (1, 4, 9, 16, 25) >>> print squares[1:4] (4, 9, 16)

5 Strings We have seen strings a couple of times before. Python distinguishes two kinds of strings: Byte strings (sometimes called ASCII strings) correspond to the strings of C and C++ and have type str. Unicode strings correspond to Java s strings and have type unicode. We restrict ourselves to byte strings. Byte strings are written "like this" most of the time. We will see alternative notations later.

6 Tuples and Lists Tuples have been mentioned a few times. We haven t seen lists before. Tuples and lists are containers for other objects. They are roughly comparable to vectors in C++/Java. Tuples are written within parentheses, lists within brackets: (2, 1, "dangerous") vs. ["red", "green", "blue"]. Tuples and lists can hold arbitrary objects, of course including other tuples and lists: ([18, 20, 22, "Null"], [("spam", [])]) The main difference between tuples and lists: Lists are mutable (may be changed). It is possible to append, insert and delete elements. Tuples are immutable (may not be changed). A tuple never changes, it will always contain the same objects. (However, the contained objects themselves may change if they are mutable, e. g. when dealing with a tuple containing lists).

7 Sequences Strings, tuples and lists have something in common: They contain other things, and these things appear in a certain order. Types with this property are called sequence types, and their instances are called sequences. All sequence types support the following operations: Concatenation: "Gambol" + "putty" == "Gambolputty" Repetition: 2 * "spam" == "spam" * 2 == "spamspam" Indexing: "Python"[1] == "y" Membership test: "yth" in "Python" Slicing: "Monty Python s Flying Circus"[6:12] == "Python" Iteration: for x in "egg"

8 Concatenation >>> print "Gambol" + "putty" Gambolputty >>> mylist = ["spam", "egg"] >>> print ["spam"] + mylist [ spam, spam, egg ] >>> primes = (2, 3, 5, 7) >>> print primes + primes (2, 3, 5, 7, 2, 3, 5, 7) >>> print mylist + primes Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: can only concatenate list (not "tuple") to list >>> print mylist + list(primes) [ spam, egg, 2, 3, 5, 7]

9 Repetition >>> print "*" * 20 ******************** >>> print [None, 2, 3] * 3 [None, 2, 3, None, 2, 3, None, 2, 3] >>> print 2 * ("parrot", ["is", dead"]) ( parrot, [ is, dead ], parrot, [ is, dead ])

10 Indexing Sequences can be indexed forwards and backwards. When indexing forwards, the first element has the index 0. When indexing backwards, negative indices are used, with the last element (first from the back) having the index 1. >>> primes = (2, 3, 5, 7, 11, 13) >>> print primes[1], primes[-1] 3 13 >>> animal = "parrot" >>> animal[-2] o >>> animal[10] Traceback (most recent call last): File "<stdin>", line 1, in? IndexError: string index out of range

11 Where are the Characters? Python has no separate datatype for characters (chars). For Python, a character is simply a string of length 1. >>> food = "spam" >>> food spam >>> food[0] s >>> type(food) <type str > >>> type(food[0]) <type str > >>> food[0][0][0][0][0] s

12 Indexing: Assigning to indices (1) Lists can be modified by assigning to indices: >>> primes = [2, 3, 6, 7, 11] >>> primes[2] = 5 >>> print primes [2, 3, 5, 7, 11] >>> primes[-1] = 101 >>> print primes [2, 3, 5, 7, 101] Again, the modified indices must be within bounds.

13 Indexing: Assigning to indices (2) Tuples and strings are immutable: >>> food = "ham" >>> food[0] = "j" Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: object doesn t support item assignment >>> pair = (10, 3) >>> pair[1] = 4 Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: object doesn t support item assignment

14 Membership test: The in operator item in seq (seq is tuple or list): True if seq contains item as an element. substr in string (string is a string): True if string contains substr as a substring. >>> print 2 in [1, 4, 2] True >>> if "spam" in ("ham", "eggs", "sausage"):... print "tasty"... >>> print "m" in "spam", "ham" in "spam", "pam" in "spam" True False True

15 Slicing Slicing is cutting a slice, i. e. a contiguous subsequence, out of a sequence: >>> primes = [2, 3, 5, 7, 11, 13] >>> print primes[1:4] [3, 5, 7] >>> print primes[:2] [2, 3] >>> print "egg, sausage and bacon"[-5:] bacon

16 Slicing: Explanation seq[i:j] returns the elements in the range [i, j), i. e. those at positions i, i + 1,..., j 1: ("do", "re", 5, 7)[1:3] == ("re", 5) If i is left out, the slice starts at position 0: ("do", "re", 5, 7)[:3] == ("do", "re", 5) If j is left out, the slice ends after the last position: ("do", "re", 5, 7)[1:] == ("re", 5, 7) If both are left out, the slice contains the whole sequence: ("do", "re", 5, 7)[:] == ("do", "re", 5, 7)

17 Slicing: Explanation (2) There are no index errors when slicing: Ranges beyond the end of the sequence are simply empty: >>> "spam"[2:10] am >>> "spam"[-6:3] spa >>> "spam"[7:] Counting from the back is also possible when slicing. For example, the last thee elements of a sequence can be obtained with seq[-3:].

18 Slicing: Step Size Using so-called extended slicing, we can also specify a step size (which may be negative): >>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> numbers[1:7:2] [1, 3, 5] >>> numbers[1:8:2] [1, 3, 5, 7] >>> numbers[7:2:-1] [7, 6, 5, 4, 3] >>> numbers[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

19 Slicing: Assigning to Slices (1) When dealing with lists, we can also assign to slices, i. e. replace part of the list by another sequence: >>> dish = ["ham", "sausage", "eggs", "bacon"] >>> dish[1:3] = ["spam", "spam"] >>> print dish ["ham", "spam", "spam", "bacon"] >>> dish[:1] = ["spam"] >>> print dish ["spam", "spam", "spam", "bacon"]

20 Slicing: Assigning to Slices (2) The assigned sequences need not have the same length as the slice that is assigned to. In fact, both may even be empty: >>> print dish ["spam", "spam", "spam", "bacon"] >>> dish[1:4] = ["baked beans"] >>> print dish ["spam", "baked beans"] >>> dish[1:1] = ["sausage", "spam", "spam"] >>> print dish ["spam", "sausage", "spam", "spam", "baked beans"] >>> dish[2:4] = [] >>> print dish ["spam", "sausage", "baked beans"] When using extended slicing (with a step size), the slice and assigned sequence must have the same length.

21 Slicing and Lists: The del Statement Instead of assigning an empty sequences to a slice, we can also use the del statement to remove individual elements or slices from a list: >>> primes = [2, 3, 5, 7, 11, "spam", 13] >>> del primes[-2] >>> primes [2, 3, 5, 7, 11, 13] >>> months = ["april", "may", "grune", "sectober", "june"] >>> del months[2:4] >>> months [ april, may, june ]

22 Iteration (1) We can iterate through a sequence by using for loops: >>> primes = [2, 3, 5, 7] >>> product = 1 >>> for number in primes:... product = product * number print product 210

23 Iteration (2) for works with all sequence types: >>> for character in "spam":... print character * 2... ss pp aa mm >>> for ingredient in ("spam", "spam", "egg"):... if ingredient == "spam":... print "tasty!"... tasty! tasty!

24 Iteration: Several Loop Variables When iterating through a sequence of sequences, several loop variables can be bound at the same time: >>> couples = [("Jupiter", "Lys"), ("Peter", "Kelly"),... ("Bob", "Liz")] >>> for x, y in couples:... print x, "is cool;", y, "is irritating."... Jupiter is cool; Lys is irritating. Peter is cool; Kelly is irritating. Bob is cool; Liz is irritating. This is an application of tuple unpacking, which we saw earlier.

25 break, continue, else When dealing with loops, the following three statements are useful: break terminates the loop ahead of time. continue terminates the current iteration of the loop ahead of time, i. e. jumps to the head of the loop and gets the next value(s) for the loop variable(s). Moreover, loops can have an else branch just like if statements. This branch is executed after finishing the loop unless the loop has been terminated with break. break, continue and else also work with the previously encountered while loops.

26 break, continue, else: Example break-continue-else.py foods_and_amounts = [("sausage", 2), ("eggs", 0), ("spam", 2), ("ham", 1)] for food, amount in foods_and_amounts: if amount == 0: continue if food == "spam": print amount, "tasty piece(s) of spam." break else: print "No spam!" # Output: # 2 tasty piece(s) of spam.

27 Modifying Lists While Iterating (1) During a loop, the object that is being iterated on should not change its size. If it does, even though we don t get hard crashes like in C++, the result can be confusing: >>> numbers = [3, 5, 7] >>> for n in numbers:... print n... if n == 3:... del numbers[0] >>> print numbers [5, 7]

28 Modifying Lists While Iterating (2) We can avoid the problem by iterating through a copy of the list: >>> numbers = [3, 5, 7] >>> for n in numbers[:]:... print n... if n == 3:... del numbers[0] >>> print numbers [5, 7]

29 Useful Functions for for Loops Some builtins are often used in the context of for loops: range and xrange enumerate zip

30 range and xrange range creates lists of integers: range(stop) returns [0, 1,..., stop-1] range(start, stop) returns [start, 1,..., stop-1] range(start, stop, step) returns [start, start + step, start + 2 * step,..., stop-1] xrange works like range, but does not return a real list, but an object of a special type, which is (more or less) exclusively intended for iterating through it. xrange conserves memory compared to range as no list needs to be created.

31 range and xrange: Examples >>> range(5) [0, 1, 2, 3, 4] >>> range(3, 30, 10) [3, 13, 23] >>> for i in xrange(3, 7):... print i, "** 3 =", i ** ** 3 = 27 4 ** 3 = 64 5 ** 3 = ** 3 = 216

32 enumerate Sometimes we need to know at which position we are within a sequence while iterating it. For this purpose, we can use the function enumerate, which takes a sequences as an argument and returns a series of pairs (index, element): >>> for i, char in enumerate("spam"):... print "At position", i, "the letter is", char... At position 0 the letter is s. At position 1 the letter is p. At position 2 the letter is a. At position 3 the letter is m. Like xrange, the enumerate function does not return a real list, but is mostly intended for for loops. More specifically, it returns a generator.

33 zip (1) The zip function accepts one or more sequences and returns a list of tuples with corresponding elements from those sequences: >>> detectives = ["Jupiter", "Peter", "Bob"] >>> girlfriends = ["Lys", "Kelly", "Liz"] >>> print zip(detectives, girlfriends) [( Jupiter, Lys ), ( Peter, Kelly ), ( Bob, Liz )] zip returns a real list.

34 zip (2) When several sequences should be iterated in parallel, zip comes useful: >>> for x, y, z in zip("ham", "spam", range(5, 10)):... print x, y, z... h s 5 a p 6 m a 7 If the input sequences are of different length, the result is as long as the shortest input.

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections 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

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python 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

More information

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

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

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

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

AI Programming CS S-02 Python

AI Programming CS S-02 Python AI Programming CS662-2013S-02 Python David Galles Department of Computer Science University of San Francisco 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use

More information

COMP1730/COMP6730 Programming for Scientists. Strings

COMP1730/COMP6730 Programming for Scientists. Strings COMP1730/COMP6730 Programming for Scientists Strings Lecture outline * Sequence Data Types * Character encoding & strings * Indexing & slicing * Iteration over sequences Sequences * A sequence contains

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries 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

More information

Python a modern scripting PL. Python

Python a modern scripting PL. Python Python a modern scripting PL Basic statements Basic data types & their operations Strings, lists, tuples, dictionaries, files Functions Strings Dictionaries Many examples originally from O Reilly Learning

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 5 Part 1 Instructor: Long Ma The Department of Computer Science Objectives Chapter 5: Sequences: Strings, Lists, and Files

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

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

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han Lesson 4: Type Conversion, Mutability, Sequence Indexing Fundamentals of Text Processing for Linguists Na-Rae Han Objectives Python data types Mutable vs. immutable object types How variable assignment

More information

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

Python for loops. Girls Programming Network School of Information Technologies University of Sydney. Mini-lecture 7 Python for loops Girls Programming Network School of Information Technologies University of Sydney Mini-lecture 7 Lists for loops More Strings Summary 2 Outline 1 Lists 2 for loops 3 More Strings 4 Summary

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 09 For Loops All materials copyright UMBC unless otherwise noted Last Class We Covered Lists and what they are used for Operations a list can perform Including

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 4 Working with Strings 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sequence of Characters We

More information

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

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi 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

More information

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

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 5 Part 1 The Department of Computer Science Objectives To understand the string data type and how strings are represented

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

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

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

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

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France [Software Development] Python (Part A) Davide Balzarotti Eurecom Sophia Antipolis, France 1 Homework Status 83 registered students 41% completed at least one challenge 5 command line ninjas 0 python masters

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

CS1 Lecture 11 Feb. 9, 2018

CS1 Lecture 11 Feb. 9, 2018 CS1 Lecture 11 Feb. 9, 2018 HW3 due Monday morning, 9:00am for #1 I don t care if you use 1, 2, or 3 loops. Most important is clear correct code for #3, make sure all legal situations are handled. Think

More information

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif Chapter 8 Working with Sequences: Strings and Lists Section 8.1 and 8.2 Bonita Sharif 1 Sequences A sequence is an object that consists of multiple data items These items are stored consecutively Examples

More information

IAP Python - Lecture 2

IAP Python - Lecture 2 IAP Python - Lecture 2 Evan Broder, Andrew Farrell MIT SIPB January 6, 2011 Higher Order Functions A function is a first-class object, so it can be returned from a function. def maketunk(n): def thunk():

More information

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

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani 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

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

UNIT 5. String Functions and Random Numbers

UNIT 5. String Functions and Random Numbers UNIT 5 String Functions and Random Numbers DAY 1 String data type String storage in data String indexing I can.. Explain the purpose of the string variable type and how it is stored in memory. Explain

More information

Slicing. Open pizza_slicer.py

Slicing. Open pizza_slicer.py Slicing and Tuples Slicing Open pizza_slicer.py Indexing a string is a great way of getting to a single value in a string However, what if you want to use a section of a string Like the middle name of

More information

CSC326 Python Sequences i. CSC326 Python Sequences

CSC326 Python Sequences i. CSC326 Python Sequences i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples

More information

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,

More information

Introduction to Python. Data Structures

Introduction to Python. Data Structures Introduction to Python Data Structures Data Structures Encapsulation & Notion of an Object Data + a set of methods (functions) that operate on the data A.foo() Linear Data Structure: List, Strings, sequences

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful

More information

String Objects: The string class library

String Objects: The string class library String Objects: The string class library Lecture 23 COP 3014 Spring 2017 March 7, 2017 C-strings vs. string objects In C++ (and C), there is no built-in string type Basic strings (C-strings) are implemented

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

Python Tutorial. Day 1

Python Tutorial. Day 1 Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 15 For Loops All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Last Class We Covered Two-dimensional lists Lists and functions Mutability

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions. Handout 2 Functions, Lists, For Loops and Tuples [ ] Functions -- parameters/arguments, "calling" functions, return values, etc. Please make sure you understand this example: def square(x): return x *

More information

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

Sequence of Characters. Non-printing Characters. And Then There Is   Subset of UTF-8. String Representation 6/5/2018. Chapter 4 Working with Strings Sequence of Characters we've talked about strings being a sequence of characters. a string is indicated between ' ' or " " the exact sequence of characters is maintained

More information

The second statement selects character number 1 from and assigns it to.

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

Episode 3 Lists and Strings

Episode 3 Lists and Strings Episode 3 Lists and Strings Lists and strings are two of the most important types in Python. For these, one variable name stands for several items, so we call them compound types. Lists Lists are much

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Data Science Python. Anaconda.  Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas. Data Science Python Anaconda Python 3.x Includes ALL major Python data science packages Sci-kit learn Pandas PlotPy Jupyter Notebooks www.anaconda.com Python - simple commands Python is an interactive

More information

UNIVERSITÀ DI PADOVA. < 2014 March >

UNIVERSITÀ DI PADOVA. < 2014 March > UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Algorithmic Thinking: Computing with Lists

Algorithmic Thinking: Computing with Lists Algorithmic Thinking: Computing with Lists So Far in Python Data types: int, float, Boolean, string Assignments, function definitions Control structures: For loops, while loops, conditionals Last Lecture

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

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

Working with Strings. Husni. The Practice of Computing Using Python, Punch & Enbody, Copyright 2013 Pearson Education, Inc. Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.

More information

Introduction to Python

Introduction to Python Introduction to Python Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows)

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

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

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky CS 115 Lecture 13 Strings Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 29 October 2015 Strings We ve been using strings for a while. What can

More information

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

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food CSCI 1101B Lists Warm-up Exercise def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food food = order( pasta ) After this program runs 1. What is the global

More information

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

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

Computing with Numbers

Computing with Numbers Computing with Numbers Example output: Numeric Data Types Numeric Data Types Whole numbers are represented using the integer data type (int for short).values of type int can be positive or negative whole

More information

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

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)

More information

Unit 2. Srinidhi H Asst Professor

Unit 2. Srinidhi H Asst Professor Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell In the python interactive shell you don t need print Creating variables

More information

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

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

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word? Motivation: How to count the number of vowels in a word? Sequences and Loops o You re given words like 'boston', 'wellesley', 'needham', 'lynn', etc. o Tasks: o count the number of vowels in a word. o

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

Strengthen Your Python Foundations

Strengthen Your Python Foundations Strengthen Your Python Foundations The code examples that are provided along with the chapters don't require you to master Python. However, they will assume that you previously obtained a working knowledge

More information

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

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

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

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

Introduction to Python

Introduction to Python Introduction to Python Michael Krisper Thomas Wurmitzer October 21, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 1 / 26 Schedule Tutorium I Dates & Deadlines Submission

More information

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

Lecture Agenda. Objects. But First... Immutable Types and Nesting. Immutable Types and Nesting COMP10001 Foundations of Computing Objects and Types: A Closer Look (Advanced Lecture) Semester 1, 2017 Tim Baldwin & Egemen Tanin Lecture Agenda This lecture: Making sense of strings, lists and functions

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

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

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ] Python Lists Chapter 8 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution.0 License. http://creativecommons.org/licenses/by/.0/. Copyright 2010,

More information

1 Lecture 5: Advanced Data Structures

1 Lecture 5: Advanced Data Structures L5 June 14, 2017 1 Lecture 5: Advanced Data Structures CSCI 1360E: Foundations for Informatics and Analytics 1.1 Overview and Objectives We ve covered list, tuples, sets, and dictionaries. These are the

More information

Strings. Genome 373 Genomic Informatics Elhanan Borenstein

Strings. Genome 373 Genomic Informatics Elhanan Borenstein Strings Genome 373 Genomic Informatics Elhanan Borenstein print hello, world pi = 3.14159 pi = -7.2 yet_another_var = pi + 10 print pi import math log10 = math.log(10) import sys arg1 = sys.argv[1] arg2

More information

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures What we will learn: Selection structures Loops What you need to know before: Data types Functions For loop While loop If selection If else structures Control structures are

More information

A Brief Introduction to Python

A Brief Introduction to Python A Brief Introduction to Python Python is an interpreted language, meaning that a program, i.e., the interpreter, is used to execute your commands one after the other. The commands can be entered interactively

More information

Crash Dive into Python

Crash Dive into Python ECPE 170 University of the Pacific Crash Dive into Python 2 Lab Schedule Today Ac:vi:es Endianness Python Thursday Network programming Lab 8 Network Programming Lab 8 Assignments Due Due by Mar 30 th 5:00am

More information

Python Review IPRE

Python Review IPRE Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information