Lists How lists are like strings

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

Ch.2: Loops and lists

CS 1110 Final, December 8th, Question Points Score Total: 100

MUTABLE LISTS AND DICTIONARIES 4

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

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

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

CS 1110 Final, December 8th, Question Points Score Total: 100

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

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

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

Write the function of following in Windows Operating System:

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

PYTHON NUMPY TUTORIAL CIS 581

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Algorithmic Thinking: Computing with Lists

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm

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

Computing with Numbers

Data Structures. Lists, Tuples, Sets, Dictionaries

Python Intro GIS Week 1. Jake K. Carr

The Dynamic Typing Interlude

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

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

Introduction to Python

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

CSC 108H: Introduction to Computer Programming. Summer Marek Janicki

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

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

Lists, loops and decisions

A Brief Introduction to Python

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

Teaching London Computing

somedata = { } somedata[ cheese ] = dairy somedata[ Cheese ] = dairy items = ( ( 3, 2 ), ( 5, 7 ), ( 1, 9 ), 0, ( 1 ) )

Collections. Lists, Tuples, Sets, Dictionaries

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

Control Structures 1 / 17

>>> * *(25**0.16) *10*(25**0.16)

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

CSCA20 Worksheet Strings

CS 102 Lab 3 Fall 2012

CS 1110 Prelim 1 October 4th, 2012

Advanced Python. Executive Summary, Session 1

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

CSCE 110 Programming I

Sequences and iteration in Python

Types, lists & functions

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2

Programming Fundamentals and Python

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

Introduction to programming using Python

Python. Karin Lagesen.

Python Programming Language

Python and Bioinformatics. Pierre Parutto

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

The Practice of Computing Using PYTHON

Scripting Languages. Python basics

Introduction to Programming in Python (2)

python 01 September 16, 2016

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

Programming in Python

CMSC201 Computer Science I for Majors

Script language: Python Data structures

CSE 115. Introduction to Computer Science I

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Lessons on Python Functions

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

CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions

Problem 1 (a): List Operations

Comp 150 Exam 2 Overview.

CS1110 Lab 6 (Mar 17-18, 2015)

Exercise: The basics - variables and types

CS177 Python Programming. Recitation 2 - Computing with Numbers

Compound Data Types 1

1 Strings (Review) CS151: Problem Solving and Programming

List of lectures. Lecture content. Imperative Programming. TDDA69 Data and Program Structure Imperative Programming and Data Structures

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

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

Introduction to Python

Expressions and Variables

Algorithmic Thinking: Computing with Lists

Final Exam Practice Questions

CMSC201 Computer Science I for Majors

CS 2316 Exam 1 Spring 2014

MEIN 50010: Python Data Structures

ISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings

Programming for Engineers in Python. Autumn

Fundamentals: Expressions and Assignment

Notebook. March 30, 2019

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

University of Texas at Arlington, TX, USA

Strings and Testing string methods, formatting testing approaches CS GMU

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Functions. Rich Enbody. From Mathematics we know that functions perform some operation and return one value.

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

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

Programming to Python

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

ENGR 102 Engineering Lab I - Computation

Transcription:

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 by all sequence types, which include lists and strings.) These include indexing, slices, addition for concatenation, multiplication for repetition, and the count and index methods. The Python Shell session below illustrates this.

=[2,5,-1.3] >>> len(s) 3 [2] -1.3 [3] Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> s[3] IndexError: list index out of range [1:] [5, -1.3] =s+[6,4,-1,2] [2, 5, -1.3, 6, 4, -1, 2] >>> for num in s[3:6]: print(num) 6 4-1 =s*2 [2, 5, -1.3, 6, 4, -1, 2, 2, 5, -1.3, 6, 4, -1, 2].count(2) 4 Figure 1. Some basic operations on lists; all the operations displayed here can also be performed with strings.

There is also an empty list. =[] >>> len(s) 0 Figure 2. The empty list. How lists are different from strings Lists are heterogeneous You can have any type of object as a list element, including another list, and you can even have different types of objects in the same list. The list s in the code below has 4 elements, all of different types.

>>> import math >>> t=[2,9,5] =['spirit level',math.pi,t,43*75] [3] 3225 [2][2] 5 [0][5] 't' [1] 3.141592653589793 Figure 3. The elements of the list s include a string, an int, a float, and another list. Lists are mutable Unlike strings, lists can be modified by assigning new values to their elements: >>>s=[1,2,3] [1]='two' [1, 'two', 3] Figure 4. Changing an element of a list; recall that this operation cannot be done with strings. You can even do this sort of thing with slices of the list, which allows you to replace whole ranges of elements with other elements:

=[3,5,9,-1,4,2] [1:4]=[2,8,-17,4,6] [3, 2, 8, -17, 4, 6, 4, 2] [5:7]=[] [3, 2, 8, -17, 4, 2] Figure 5. Replacing ranges of list elements. Mutability of lists permits a bunch of convenient methods for carrying out these and other such mutating operations on lists. See the table in Section 4.6.4 of the Standard Library Reference. Here is a brief sample. =[1,2,3].append(4) [1, 2, 3, 4].extend([5,6,7]) >>> x=s.pop() >>> x 7.insert(0,x) [7, 1, 2, 3, 4, 5, 6] Figure 6. Methods that modify lists. Observe that these methods do not create a new list, and do not return the altered list as a value. By the way, the append method, which allows you to attach an item to the end of a list, is probably the one that you will use the most.

There are important differences between these mutating operations and some of the string methods we saw, as well as operations, like concatenation, that work on both mutable and immutable sequence types. The mutating operations modify the object itself and do not return the new list as a value. (In contrast, a string method like s.lower() creates a new string, which it returns as a value, and leaves s unchanged.) 1=[1,2,3] >>> t1=s1 1.append(4) >>> t1 [1, 2, 3, 4] 2=[1,2,3] >>> t2=s2 2=s2+[4] 2 [1, 2, 3, 4] >>> t2 [1, 2, 3] Figure 7. After appending a new element, s1 and t1 still point to the same list, which has now been changed. But concatenating s2 with [4] leads to the creation of a new list, while the value of t2 is unchanged.

As an exercise, try to predict what each of the following statements does. They are all intended to set change the value of s from [1,2,3,4] to [1,2,3,4,5], but they do not all do this; some of them do something else, and some of them cause a runtime error: (a) s.append(5) (b) s.extend(5) (c) s.append([5]) (d) s.extend([5]) (e) s= s+5 (f) s=s+[5] (g) s=s.append(5) Figure 8 Test yourself---what do these statements do? Special operations on lists If the items in a list can be compared to one another with < and >, then built-in functions min and max (which also work for strings) return the minimum and maximum elements of a list. The method sort sorts the list in place, modifying it in the process. If the elements in a list are numbers, then the built-in function sum computes the sum of the list elements. =[-9,14.2,7.3,1.00003,-46.8] >>> min(s) -46.8 >>> max(s) 14.2 um(s) -33.299969999999995.sort() [-46.8, -9, 1.00003, 7.3, 14.2]

Lists as function arguments One consequence of the mutability of lists is that when a list is passed as an argument to a function, the list can be altered as a result of executing the function. This cannot happen with the data types (int, float, str) that we have seen so far.

def f(u,v,w,x,y): u=7 v=[7] w[0]=7 x=x+[7] y.append(7) >>> a=6 >>> b=[6] >>> c=[6] >>> d=[6] >>> e=[6] >>> f(a,b,c,d,e) >>> print(a) 6 >>> print(b) [6] >>> print(c) [7] >>> print(d) [6] >>> print(e) [6, 7] Figure 10. Passing a list to a function can change the list if the function applies list-mutating operations.

List Comprehension Suppose you have a list u of floats and you want to create a list of the square roots of the numbers in the list. We can do it with the following code. >>> u = [4,7,3,9,1.5,2,4] >>> import math >>> v=[] >>> for x in u: v.append(math.sqrt(x)) >>> v [2.0, 2.6457513110645907, 1.7320508075688772, 3.0, 1.224744871391589, 1.4142135623730951, 2.0] Figure 11. Making a list of the square roots of the elements of a list. Python offers a nice shortcut, called list comprehension, inspired by a standard mathematical notation for sets: If L is a set of numbers, then the set of square roots is denoted by.! x!x L! In Python, we can mimic this notation and write, in place of our construction of the list v above

v=[math.sqrt(x) for x in u] Figure 12. The same operation done in a single line with list comprehension. As another example, here we take a list of strings and convert them all to upper-case. trings = ['father','mother','brother','sister','cousin','uncle', 'aunt'] >>> w = [s.upper() for s in strings] >>> w ['FATHER', 'MOTHER', 'BROTHER', 'SISTER', 'COUSIN', 'UNCLE', 'AUNT'] Figure 13 Another list comprehension example. We can go a little farther with our square root example. Here we use list comprehension with the random number generator to create a list containing both positive and negative values, and then use list comprehension again with 'if' to filter out negative values before finding the square root: u=[random.random()-0.5 for x in range(8)] >>> u [0.22717774659875167, 0.1791265809279945, -0.1342798505673375, 0.45442208410686136, -0.11774922039818136, 0.38142814415542703, 0.4954685313885897, -0.1713835869379009] >>> v=[math.sqrt(x) for x in u if x>=0] >>> v [0.476631667641536, 0.423233482758624, 0.6741083622881868, 0.6175986918342906, 0.7038952559781816] Figure 14 List comprehension with 'if'.

The general form for list comprehension is [e(x) for x in my_sequence if c(x)] where x is a new variable, e is any expression (usually involving x) and c is a boolean-valued expression (also typically involving x). my_sequence can be an object of any sequence type (a list, a string, a range..) What does [3 for x in range(10)] do? How about [x for x in range(10) if x<0]?