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

Similar documents
Introduction to Python. Data Structures

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

Introduction to programming using Python

Topic 7: Lists, Dictionaries and Strings

Lists How lists are like strings

Python Intro GIS Week 1. Jake K. Carr

Python Programming Exercises 3

Chapter 8 : Computer Science. Datastructures: Class XII ( As per CBSE Board) lists, stacks, queues. Visit : python.mykvs.in for regular updates

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

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

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

Episode 3 Lists and Strings

Compound Data Types 2

ENGR/CS 101 CS Session Lecture 12

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 12 LISTING TO ONE SIDE MICHAEL GROSSBERG

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

MULTIPLE CHOICE. Chapter Seven

Python Review IPRE

Introduction to Python

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

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

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

Python Review IPRE

#5: Strings, Lists Reading: Chapter 4 and 5

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

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

Types, lists & functions

CIS192 Python Programming

Script language: Python Data structures

Babu Madhav Institute of Information Technology, UTU 2015

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

Introduction to Problem Solving and Programming in Python.

Using Lists (Arrays) Notes

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

Sequence Types FEB

CS Advanced Unix Tools & Scripting

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

Data Structures. Lists, Tuples, Sets, Dictionaries

Lists. Ruth Anderson University of Washington CSE 160 Spring 2015

OOP and Scripting in Python Advanced Features

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

Lists. Ruth Anderson University of Washington CSE 160 Winter 2017

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

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

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

Level 3 Computing Year 2 Lecturer: Phil Smith

University of Texas at Arlington, TX, USA

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Python. Karin Lagesen.

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

Python Lists and Dictionaries CS 8: Introduction to Computer Science, Winter 2019 Lecture #13

COLLEGE OF ENGINEERING, NASHIK-4

Announcements COMP 141. Accessing Characters Review. Using len function 10/30/2017. Strings II. Reminders: Program 6 - due 11/2

Notebook. March 30, 2019

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

Variable and Data Type 2

MITOCW watch?v=rvrkt-jxvko

Lists, loops and decisions

Spring INF Principles of Programming for Informatics. Manipulating Lists

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

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources

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

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

Basic Python Revision Notes With help from Nitish Mittal

Lessons on Python Functions

MUTABLE LISTS AND DICTIONARIES 4

ENGR 102 Engineering Lab I - Computation

JavaScript Functions, Objects and Array

The Practice of Computing Using PYTHON

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

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

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

B. V. Patel Institute of Business Management, Computer & Information Technology, UTU 2013

Sequences and iteration in Python

Python for Non-programmers

Unit 2. Srinidhi H Asst Professor

F# - LISTS. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example

Introduction to String Manipulation

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 7. Fall 2018

CS 1110: Introduction to Computing Using Python Lists and Sequences

A tuple can be created as a comma-separated list of values:

Collections. Lists, Tuples, Sets, Dictionaries

CS Summer 2013

Merge HL7 Toolkit Segment Map User Interface (UI) Sample Application Guide v.4.7.0

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

Some material adapted from Upenn cmpe391 slides and other sources

Part III Appendices 165

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

DM502 Programming A. Peter Schneider-Kamp.

Python and Bioinformatics. Pierre Parutto

Introduction to: Computers & Programming: Strings and Other Sequences

Open a file from the selection of demonstration examples provided using the [Demo] button on the File-Open dialogue.

MEIN 50010: Python Data Structures

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

Review 4. Lists and Sequences

CE151-4-AU UNIVERSITY OF ESSEX. Sample Examination Questions 2011 INTRODUCTION TO PROGRAMMING

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013

F# - ARRAYS. Arrays are fixed-size, zero-based, mutable collections of consecutive data elements that are all of the same type.

Transcription:

Chapter 6: List What we will learn: List definition Syntax for creating lists Selecting elements of a list Selecting subsequence of a list What you need to know before: Data types Assignments List Sub-list Elements Index Position 6.1 Definition The list is the most versatile data structure Python uses. It is a mutable collection of data items which can be of the same or different data types. When a data collection is mutable, it means we can change individual items in the collection. The items are written between square brackets and are separated by commas; they can be assigned to a variable. <variable> = [<list_item>, <list_item>,...] Where <list_item> can be empty, or any data type. 6.1.1 Selecting Individual Elements As a list is a compound data type, we can select individual elements by indexing these. Using Negative Index A negative index will return the value at its position from the end of the list.

6.2 List Operations Concatenation We can concatenate a list by using the concatenation operation (+). Notice that z now stores the items of x and y. Multiplication The multiplication operation has a similar effect on lists as on strings. Notice that multiplying by three produces the list three times. Selecting a Subsequence in the List Slicing We can select a subsequence in a list by using the slice operation. The slice operation (:) is used to specify the starting and end points to return a section of a list. Sub-selection is also called slicing the list. It is important to note that sub-selection will return a virtual copy of the list and does not mutate the original list; from the example above, days is unaffected, hence printing the value of days will give the entire list. Important: The first number in the slice operation [<start> : <end>] is the starting point and the last number is the ending point. If these are left blank then Python assumes that the start position is the beginning of the list and the end position is the end of the list.

6.3 Editing a List Because lists are mutable, unlike strings, it is possible to change the values in a list. Note that we can assign a new edit list by referring to its position and assigning a new value. 6.4 Lists of Lists Python allows us to have lists of lists: We can make a few observations from the script above. It is possible to have different data types in the same list; above we used string and an integer to represent a year. We can have lists of lists Olympic_host is a list containing three elements where each element is itself a list containing the Olympic host city and year. We can access the individual element in each list by sub-indexing the position, in the example above Olympic_host[1][0]. 6.5 List Methods There are various methods defined on lists, below we will examine some of these methods. append() Append will add an element to the end of the list. Append mutates (changes) the list instead of creating a new list, the result of invoking append on a list is that the calling list will have the new element added to the end. <list>.append(<element>) <list> is the list to be appended. <element> is the element to be appended to the list.

Notice that after a call to append with argument 45, the list x now has 45 appended to the end. insert() Insert is used to insert an element at a given index. Insert mutates the existing list with the new element inserted. <list>.insert(<position>, <element>) <list> is the list that the element should be inserted into. <position> is the position in the list that the element will be inserted, recall that the first position is position zero (0). <element> is the element to be inserted into the list. Notice that after the insert function is invoked on the list x, 35 is now inserted in position 3. sort() The sort function will sort the list. <list>.sort() <list> is the list to be sorted.

count() Count will return the number of occurrences of an element in a list. <list>.count(<element>) <list> is the list that the count is invoked on. <element> is the element that you search for the occurrence of. Notice that there are two occurrences of 2 and only one of occurrence of 15; there are no occurrences of 45 in the list and hence y.count(45) will return 0. extend() Extend mutates a list and has the effect of adding a second list to the first list. Note that the second list will still exist in its original state. <list1>.extend(<list2>) <list1> is the list to be mutated. <list2> is the list that will be added to list 1. After x.extend(y) is called, x now contains the elements of both x and y; however, y is unchanged and still exists.

pop() The pop method will remove and return an element from the list. By default pop() invoked in a list will remove and return the last element in a list. You can optionally send the index of an element to be removed from the list and pop() will return that element. <list>.pop() OR <list>.pop([<index>]) <list> is the list with the elements. <index> is the optional position of the element to be removed from the list. In the second example we will remove element one. Recall that element one is the second element in the list. remove() Remove will delete the first occurrence of the given value in a list. If the element does not occur in the list then a value error is returned. <list>.remove(<element>) <list> is the list with the elements. <element> is the element to be removed from the list. After x.remove(5), 5 is removed from the list.

reverse() reverse() will reverse the elements in a list; that is the first element becomes last, second becomes next to last and so on, until the last element becomes first. <list>.reverse() <list> is the list to be reversed. index() index() will return the position of the first occurrence of the given value. index() will return a value error if the value does not exist in the list. <list>.index(<element>) <list> is the list to be searched. <element> is the value whose position we are interested in. 6.6 List Methods len() In 3.2.3 we discussed the len() operator and used it to find the length of a string; we explained that this can be used on any collection of objects. It is worth pointing out that we can use the len() operator to find out the number of elements in a list.

In Operator The in operator discussed in 3.3 will test if an object is a member of a collection. We will discuss two additional operators that can be used with lists, namely min() and max(). min() The min() operator will return the smallest value in the list. min(<list>) <list> is the list that we want to find the smallest element of. Notice that min() will compare both strings and numeric data type. max() The max() operator will return the largest value in the list. max(<list>) <list> is the list that we want to find the largest element of.