CHAPTER 4: Lists, Tuples and Dictionaries

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

Tuples. Tuples 1 A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference is that tuples can't be.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Guide to Programming with Python
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Lists Introduction to Computing Science and Programming I.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
2007 Monthly Calendar You can print this template to use it as a wall calendar, or you can copy the page for any month to add it to your own presentation.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 1 Introduction to Computer Programming Chapter 5: Lists and Dictionaries Michael Scherger Department.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Built-in Data Structures in Python An Introduction.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Arrays Collections of data Winter 2004CS-1010 Dr. Mark L. Hornick 1.
String and Lists Dr. José M. Reyes Álamo.
10 - Python Dictionary John R. Woodward.
Python Variable Types.
Algorithmic complexity: Speed of algorithms
Tuples and Lists.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Chapter 4 Lists In this chapter, we look at a means of structuring and accessing a collection of data. In particular, we look at a way of organizing.
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
CS 100: Roadmap to Computing
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Subroutines in Computer Programming
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Quiz 2 this week.
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
8 – Lists and tuples John R. Woodward.
4. sequence data type Rocky K. C. Chang 16 September 2018
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
String and Lists Dr. José M. Reyes Álamo.
Algorithmic complexity: Speed of algorithms
Topics Sequences Introduction to Lists List Slicing
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Teacher name August phone: Enter text here.
CISC101 Reminders Assignment 2 due today.
Algorithmic complexity: Speed of algorithms
15-110: Principles of Computing
Bryan Burlingame Halloween 2018
COMPUTER PROGRAMMING SKILLS
Topics Sequences Introduction to Lists List Slicing
Python Review
Intro to Computer Science CS1510 Dr. Sarah Diesburg
For loop Using lists.
Lists [] First = [1, 2, 3, 4] Second = list[range(1,5)]
Introduction to Dictionaries
Class code for pythonroom.com cchsp2cs
Enclosing delimiters Python uses three style of special enclosing delimiters. These are what the Python documentation calls them: {} braces # Sometimes.
Dictionary.
2015 January February March April May June July August September
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

CHAPTER 4: Lists, Tuples and Dictionaries COMPUTER PROGRAMMING SKILLS 1439-1440

Outline Lists Functions and Methods for Lists Tuples Functions and Methods for Tuples Dictionaries Functions and Methods for Dictionaries Exercises

Lists A list is an object that holds a collection of objects; it represents a sequence of data. In that sense, a list is similar to a string, except a string can hold only characters. A list can hold any Python object. A list need not be homogeneous; that is, the elements of a list do not all have to be of the same type. Creating a simple list L: L = [1,2,3] Use square brackets to indicate the start and end of the list, and separate the items by commas. The empty list is []. It is the list equivalent of 0 or ''.

Lists If you have a long list to enter, you can split it across several lines, like below: nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] We can use eval(input()) to allow the user to enter a list. You can use the print function to print the entire contents of a list. L = eval(input('Enter a list: ')) print('The list is', L) Enter a list: [5,7,9] The list is [5,7,9]

Lists Lists can contain all kinds of things, even other lists. For example, the following is a valid list: L= [1, 2.718, 'abc', [5,6,7]] L = [1, 2.718, 'abc', [5,6,7]] print (L) [1, 2.718, 'abc', [5,6,7]]

Lists There are a number of things which work the same way for lists as for string. len — The number of items in L is given by len(L). Indexing and slicing — These work exactly as with strings. For example, L[0] is the first item of the list L and L[:3] gives the first three items. index and count — These methods work the same as they do for strings. + and * — The + operator adds one list to the end of another. The * operator repeats a list.

Functions and Methods for Lists There are several built-in functions that operate on lists. Here are some useful ones: For example, the following computes the average of the values in a list L: average = sum(L)/len(L)

Functions and Methods for Lists Here are some list methods:

Functions and Methods for Lists Important note There is a big difference between list methods and string methods: String methods do not change the original string, but list methods do change the original list. To sort a list L, just use L.sort() and not L=L.sort(). In fact, the latter will not work at all.

Tuples A tuple is essentially an immutable list. Below is a list with three elements and a tuple with three elements: Tuples are enclosed in parentheses, though the parentheses are actually optional. Indexing and slicing work the same as with lists. As with lists, you can get the length of the tuple by using the len function, and, like lists, tuples have count and index methods. However, since a tuple is immutable, it does not have any of the other methods that lists have, like sort or reverse, as those change the list. L = [1,2,3] t = (1,2,3)

Tuples One reason why there are both lists and tuples is that in situations where speed really matters, tuples are generally faster than lists. The flexibility of lists comes with a corresponding cost in speed. To convert an object into a tuple, use tuple. The following example converts a list and a string into tuples: t1 = tuple([1,2,3]) t2 = tuple('abcde')

Dictionaries A dictionary is a more general version of a list. Here is a list that contains the number of days in the months of the year. If we want the the number of days in January, use days[0]. December is days[11] or days[-1]. Here is a dictionary of the days in the months of the year: To get the number of days in January, we use days['January']. One benefit of using dictionaries here is the code is more readable, and we don’t have to figure out which index in the list a given month is at. Dictionaries have a number of other uses, as well. days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] days = {'January':31, 'February':28, 'March':31, 'April':30, 'May':31, 'June':30, 'July':31, 'August':31, 'September':30, 'October':31, 'November':30, 'December':31}

Dictionaries To declare a dictionary we enclose it in curly braces, {}. Each entry consists of a pair separated by a colon. The first part of the pair is called the key and the second is the value. The key acts like an index. Here is a simple dictionary: So in the first pair, 'A':100, the key is 'A', the value is 100, and d['A'] gives 100. Keys are often strings, but they can be integers, floats, and many other things as well. You can mix different types of keys in the same dictionary and different types of values, too. d = {'A':100, 'B':200}

Functions and Methods for Dictionaries To change d['A'] to 400: d['A']=400 To add a new entry to the dictionary, we can just assign it, like below: d['C']=500 To delete an entry from a dictionary, use the del operator: del d['A'] To copy a dictionary, use its copy method. Here is an example: d2 = d.copy() The empty dictionary is {}, which is the dictionary equivalent of [] for lists or '' for strings. d = {'A':100, 'B':200}

Functions and Methods for Dictionaries The dict function is another way to create a dictionary. d = dict([('A',100),('B',300)]) This creates the dictionary {'A':100,'B':300}. This way of building a dictionary is useful if your program needs to construct a dictionary while it is running.

Exercises What happens if you attempt to access an element of a list using a negative index? What Python statement produces a list containing the values 45, −3, 16 and 8, in that order? Given the statement lst = [10, -4, 11, 29] What expression represents the very first element of lst? What expression represents the very last element of lst? What is lst[0]? What is lst[3]? What is lst[1]? What is lst[-1]? What is lst[-4]? Is the expression lst[3.0] legal or illegal?

Exercises Given the list lst = [20, 1, -34, 40, -8, 60, 1, 3] evaluate the following expressions: lst lst[0:3] lst[4:8] lst[4:33] lst[-5:-3] lst[-22:3] lst[4:] lst[:] lst[:4] lst[1:5] len(lst)

Exercises Are tuples mutable or immutable? Consider the tuple tpl defined as tpl = 7, 10, -3, 18, 6, 10 Provide one assignment statement that uses tuple unpacking to assign x to the first element and y to the last element. What happens when an executing program attempts to retrieve a value using a key that is not present in the dictionary? What happens when an executing program attempts to associate a value with a key that is not present in the dictionary? Are dictionaries mutable or immutable?