Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 4: Lists, Tuples and Dictionaries

Similar presentations


Presentation on theme: "CHAPTER 4: Lists, Tuples and Dictionaries"— Presentation transcript:

1 CHAPTER 4: Lists, Tuples and Dictionaries
COMPUTER PROGRAMMING SKILLS

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

3 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 ''.

4 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]

5 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]]

6 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.

7 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)

8 Functions and Methods for Lists
Here are some list methods:

9 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.

10 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)

11 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')

12 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}

13 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}

14 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}

15 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.

16 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?

17 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)

18 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?


Download ppt "CHAPTER 4: Lists, Tuples and Dictionaries"

Similar presentations


Ads by Google