Python Lists and Loops



Similar documents
Python Loops and String Manipulation

Introduction to Python

Exercise 1: Python Language Basics

Exercise 4 Learning Python language fundamentals

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Chapter 2 Writing Simple Programs

CS106A, Stanford Handout #38. Strings and Chars

OA3-10 Patterns in Addition Tables

Programming in Access VBA

Third Southern African Regional ACM Collegiate Programming Competition. Sponsored by IBM. Problem Set

Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

A Short Course in Logic Example 8

Working with forms in PHP

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

Udacity cs101: Building a Search Engine. Extracting a Link

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Moving from CS 61A Scheme to CS 61B Java

Decision Logic: if, if else, switch, Boolean conditions and variables

Computer Science 217

Part 1 Foundations of object orientation

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Encoding Text with a Small Alphabet

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

NF5-12 Flexibility with Equivalent Fractions and Pages

A Concrete Introduction. to the Abstract Concepts. of Integers and Algebra using Algebra Tiles

Computer Programming In QBasic

Introduction to Python

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Python Programming: An Introduction to Computer Science

Getting Started in Tinkercad

Writing Simple Programs

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Microsoft Access 3: Understanding and Creating Queries

Hypercosm. Studio.

paragraph(s). The bottom mark is for all following lines in that paragraph. The rectangle below the marks moves both marks at the same time.

CS 1133, LAB 2: FUNCTIONS AND TESTING

Programming Exercises

Beginning to Program Python

NLP Lab Session Week 3 Bigram Frequencies and Mutual Information Scores in NLTK September 16, 2015

Databases in Microsoft Access David M. Marcovitz, Ph.D.

Ad Hoc Create Table of Contents

An Introduction to Number Theory Prime Numbers and Their Applications.

Algorithm Design and Recursion

STEP 0: OPEN UP THE PYTHON EDITOR. If python is on your computer already, it's time to get started. On Windows, find IDLE in the start menu.

GUIDE: How to fill out the Excel spreadsheet Introduction There is a total of 31 fields Purpose of this guide General Notes: Very important:

2 HOW DOES TRADING WORK?. 4 HOW THE SYSTEM WORKS. 6 WHAT IF IT GOES WRONG?. 13 A RECAP. 15 BANKROLL. 16 A SUCCESSFUL TRADE EXAMPLE.

Welcome to Introduction to programming in Python

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Install Java Development Kit (JDK) 1.8

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introduction to Computer Science I Spring 2014 Mid-term exam Solutions

Chapter 15 Functional Programming Languages

Command Line - Part 1

PL / SQL Basics. Chapter 3

COMSC 100 Programming Exercises, For SP15

Chapter 7. Functions and onto. 7.1 Functions

Lecture 5: Java Fundamentals III

Limitation of Liability

A a B b C c D d. E e. F f G g H h. I i. J j K k L l. M m. N n O o P p. Q q. R r S s T t. U u. V v W w X x. Y y. Z z. abcd efg hijk lmnop qrs tuv wx yz

Command Scripts Running scripts: include and commands

First Bytes Programming Lab 2

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

PYTHON Basics

X1 Professional Client

Pseudo code Tutorial and Exercises Teacher s Version

Excel Intermediate Session 2: Charts and Tables

Data Storage. Chapter 3. Objectives. 3-1 Data Types. Data Inside the Computer. After studying this chapter, students should be able to:

Pre-Algebra Lecture 6

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Outline Basic concepts of Python language

VLOOKUP Functions How do I?

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

Informatica e Sistemi in Tempo Reale

Binary Representation. Number Systems. Base 10, Base 2, Base 16. Positional Notation. Conversion of Any Base to Decimal.

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

6.170 Tutorial 3 - Ruby Basics

ESPResSo Summer School 2012

Chapter 2. Making Shapes

Anyone Can Learn PROC TABULATE

1 Installing and Running Python

Primes. Name Period Number Theory

VISUAL ALGEBRA FOR COLLEGE STUDENTS. Laurie J. Burton Western Oregon University

Excel Intermediate. Table of Contents UPPER, LOWER, PROPER AND TRIM...28

Example of a Java program

Compiler Construction

Using SQL Queries in Crystal Reports

Introduction to Python

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Computer Science for San Francisco Youth

Sorting. Lists have a sort method Strings are sorted alphabetically, except... Uppercase is sorted before lowercase (yes, strange)

Access Part 2 - Design

Computational Mathematics with Python

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Transcription:

WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show you how. We ll also talk about the Python for loop, which is designed specifically for working with lists, and show you a few more tricks with strings and integers. 1 Data structures Imagine a Python program to store a list of authors names. Given what we ve taught you so far, you would need a separately named variable to hold each author s name: >>> name1 = "William Shakespeare" >>> name2 = "Jane Austen" >>> name3 = "J.K. Rowling" Every time you wanted to do anything you d need to mention them individually, e.g. printing a list of authors: >>> print name1 William Shakespeare >>> print name2 Jane Austen This would just get crazy as the number of authors grows! Luckily programming languages provide ways of efficiently storing and accessing groups of values together: called data structures. 2 Lists The simplest data structure in Python, a list, is used to store a list of values (not surprisingly!) of any type: >>> odds = [1, 3, 5, 7, 9] >>> colours = [ red, blue, green, yellow ] The first example is a list of odd integers and the second a list of colour names as strings. Lists are created using a comma separated list of values surrounded by square brackets. Lists hold a sequence of values (like strings hold a sequence of characters). This means items in the list can be accessed using subscripting (a.k.a. indexing) just like strings: >>> odds[0] 1 >>> colours[-1] yellow Slicing also works like on strings to create a new sublist: >>> colors[:2] [ red, blue ] c National Computer Science School 2005-2009 1

An empty list is created using just square brackets: >>> values = [] We can find out the length of a list just like a string: >>> len(colours) 4 Basically, almost every way of accessing one or more characters in a string also works in a similar way to access elements from a list. But lists allow you to store any type of values, not just characters. 3 Authors names with lists Lists really simplify our author names problem because we can use a single list (in a single variable) to hold all the authors names: >>> authors = [ William Shakespeare, Jane Austen, J.K. Rowling ] and we can access each author using an integer index: >>> authors[1] Jane Austen and even better, we can print them out using a while loop: >>> i = 0 >>> while i < len(authors):... print authors[i]... i += 1 William Shakespeare Jane Austen J.K. Rowling or for that matter check if we have a particular author: >>> J.K. Rowling in authors >>> Dan Brown in authors False If we know an element is in the list, we can then find its position: >>> authors.index( William Shakespeare ) 0 Notice that these snippets work no matter how many authors we have and where they appear in the list. 4 Lists are mutable Although you can t modify characters in an existing string, the elements in a list can be modified by assigning to subscripts and slices (the Python documentation calls strings mutable): >>> values = [1, 2, 3, 4] >>> values[-1] = 5 >>> values [1, 2, 3, 5] c National Computer Science School 2005-2009 2

5 for loops The while loop takes 4 lines of code to print the names, because we need to initialise the loop counter, check it is less than the length of the list, and remember to increment it at the end. Looping over lists is so common that there s an easier way: >>> colours = [ red, blue, green ] >>> for col in colours:... print col red blue green A for loop begins with the keyword for and ends with a colon (because it s a control structure). The col following for is a variable. Each element from the list colours will be assigned to the variable col in turn, and each time the indented body of the loop will then be run. From the output above we can see that col is assigned the values red, blue, and green in order because the statement print col is printing out those values. 6 range function Calling range(n) returns a list of integer values, starting from zero and going up to n - 1: >>> range(5) [0, 1, 2, 3, 4] This is often used with for to loop over a range of integers: >>> for i in range(3):... print i 0 1 2 range can also take a second value: >>> range(5, 10) [5, 6, 7, 8, 9] in which case range returns a list starting at the first value, and going up to but not including the last value. Finally, if you give range a third value, it steps through the values by that amount: >>> range(2, 10, 2) [2, 4, 6, 8] We can use this trick with negative numbers as well: for i in range(10, 0, -1): print i, print Running this example produces the numbers 10 down to 1 on a single line: 10 9 8 7 6 5 4 3 2 1 c National Computer Science School 2005-2009 3

Notice in this example, the print i is followed by a comma. This causes print not to add a newline to the end. So to put a newline after all of the numbers we put a separate print outside of the loop. The way range works should remind you of something else: it works in exactly the same way as slices do for strings and lists. 7 Lists of characters and words Lists can be constructed from strings using the list builtin function. >>> list( abcd ) [ a, b, c, d ] This is useful if you need to modify individual characters in a string. Often we want to split a string into a list of pieces, for example splitting a sentence into individual words. The split method of strings creates a list of words: >>> line = the quick brown fox jumped over the lazy dog >>> words = line.split() >>> words [ the, quick, brown, fox, jumped, over, the, lazy, dog ] This is useful for checking if a word is in a string: >>> jumped in words which is different to checking if a substring is in a string: >>> jump in line # jump appears in the string >>> jump in words # but not as a separate word False 8 Joining a list of strings Another useful string method is join which joins a list of strings back together using a string as a separator: >>> sep = : >>> values = [ a, b, c, d, e ] >>> sep.join(values) a:b:c:d:e You ll often see a literal string (like the space ) used: >>>.join(values) a b c d e and another common trick is to join a list with an empty string: >>>.join(values) abcdef c National Computer Science School 2005-2009 4

9 Appending, sorting and reversing There are various list methods that can be used to modify lists: >>> pets = [ dog, mouse, fish ] >>> pets.append( cat ) >>> pets [ dog, mouse, fish, cat ] The append method adds an item to the end of the list. >>> pets.sort() >>> pets [ cat, dog, fish, mouse ] The sort method sorts the items in order, e.g. strings in alphabetical order and numbers in ascending order. >>> pets.reverse() >>> pets [ mouse, fish, dog, cat ] The reverse method reverses the order of the entire list. Just like the string methods we saw last week, notice that calls to list methods have the list they operate on appear before the method name, separated by a dot, e.g. pets.reverse(). Any other values the method needs to do its job is provided in the normal way, e.g. cat is given as an extra argument inside the round brackets in pets.append( cat ). Unlike methods applied to strings, notice that these methods modify the original lists rather than creating new ones and so they don t return a value. You can tell this because there is no output when you type them into the interpreter, so we need to puts pets on a separate line to see what happened to our list. 10 Loops + lists If we want to print the words across the screen rather than one per line we can add a comma after the print statement like this: >>> words = [ James, was, here ] >>> for w in words:... print w,... James was here Another example is reading in multiple lines to produce a list of strings: lines = [] line = raw_input() while line!= : lines.append(line) line = raw_input() print lines This program will keep reading lines until a blank line is entered, that is, until you press Enter on a new line without typing anything before it. Hello World how are you? [ Hello World, how are you? ] c National Computer Science School 2005-2009 5

Let s just quickly analyse the last program to confirm you understand loops and lists. The first line creates an empty list using empty square brackets lines = []. The next line reads the first line of input from the user by calling raw_input. This line is also the initialisation statement for the loop, setting the variable line ready for the conditional expression. Now we have the loop itself. Here we are using a while loop because we don t know how many lines there might be entered by the user. We will stop when raw_input returns us no data, that is, an empty string. The while statement needed to continue reading until the empty string condition is while line!=. It turns out we can abbreviate this further because Python treats the empty string (or a list for that matter) as equivalent to False. Any other value (e.g. the string Hello World ) is. This means we can write while line!= : as simply while line:. 11 More String methods Last week we showed you how to call a method on a string object (like upper), and introduced a couple of string methods for converting strings to uppercase and lowercase, and replacing bits of a string with other strings, and we saw the split and join methods for strings above. Here are a few more string tricks... Checking if a string starts or ends with a substring: >>> s = "hello world" >>> s.startswith( hello ) >>> s.endswith( rld ) Removing whitespace from around a string: >>> s = " abc " >>> s.strip() abc >>> s.lstrip() abc >>> s.rstrip() abc Finding the index of a character in a string: >>> s = "hello world" >>> s.find( w ) 6 >>> s.find( x ) -1 c National Computer Science School 2005-2009 6