# Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.

## Presentation on theme: "Chapter 6 Lists and Dictionaries CSC1310 Fall 2009."— Presentation transcript:

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009

Lists Most flexible ordered collection of arbitrary objects (numbers, strings, lists) Most flexible ordered collection of arbitrary objects (numbers, strings, lists)  a place to collect other objects  left- to-right order Accessed by offset Accessed by offset  indexing, slicing and concatenation Variable length, heterogeneous, arbitrarily nestable Variable length, heterogeneous, arbitrarily nestable  unlike strings, list can grow and shrink in place  lists may contain any sort of object  you can create lists of lists of lists

Lists Mutable object type Mutable object type  deletion, index/slice assignment Arrays of object references Arrays of object references  Lists contain zero or more references to other objects.  Inserting an object into a data structure stores a reference to the object, not a copy of it. >>>L1=[] >>>L1=[] # an empty list>>>L2=[‘abc’,4]>>>L3=[1,2,L2,L1] >>>L4=range(4) >>>L4=range(4) #makes list of integers 0, 1, 2, 3

Basic operations: len(), +, *,in len(L1)L1. len(L1) returns number of items in the list L1. >>>len([1,2,3,[4,5]]) L1+L2 (concatenation) L1L2 L1+L2 (concatenation) creates a new list by joining operands L1 and L2. >>>[1,2,3] + [‘a’,’b’,’c’] L1*i (repeat)L1i L1*i (repeat) adds L1 to itself i times. >>> [‘ok’]*3 obj1 in L1 (membership)obj1 L1 obj1 in L1 (membership) returns true if obj1 is item of the list L1; otherwise, returns false. >>>’a’ in [1,2,’a’] >>>[2,3] in [1,2,3] >>>[2,3] in [1,[2,3]]

Strings and Lists You can not concatenate string and list ``, str(), % List to string: ``, str(), % `` >>>`[1,2,3]`+’aa’ str() >>>str([1,2,3])+’aa’ %s% >>>’%saa’ % [1,2,3] list (str) String to list: list (str) >>>l1=[1,2,3] >>>str=‘abc’ >>>l1+list(str) L1=str1.split(str2) str1 str2 L1=str1.split(str2) chops up a str1 into a list of substrings around a delimiter string str2. >>>a=“aaa bbb cc” >>>cols=a.split(“ ”)

Indexing and Slicing Indexing and slicing work the same way as for strings. >>>list=[‘aa’,’bb’,1.2,[3,4]] >>>list[1],list[2],list[3],list[-2] >>>list[::-1],list[2:] list[i][j] Indexing sublist list[i][j] >>>list[-1][1] >>>L1=[1,[2,3,[4,5,[6,7]]]] >>>L1[1][2][1],L1[1][2][2],L1[1][2][2][0] L1.index(item) To find index of item in list, use L1.index(item) >>>L1.index(1)

Matrixes Matrix can be represented as a list with nested sublists. >>>matrix=[[1,2,3],[4,5,6],[7,8,9]] To get one row, use one index. >>>matrix[0] To get an item, use two indices. >>>matrix[1][0] >>>matrix[0][2] Lists can naturally span multiple lines.

Changing Lists In-Place You can change list by assigning to a particular item (offset), or an entire section (slice) >>>list=[‘aa’,’bb’,1.2,[3,4]] >>>list[3]=“key” >>>list[1:3]=[5,6] >>>list[1:3]=[] #deletion Modify list directly rather than create new list.

List Methods Methods provide type-specific functions. L1.append(obj)obj L1 L1.append(obj) tacks a single item (obj) onto the end of the list L1. append()+ append() changes in place; + creates new list. >>>list=[3,2,’bike’] >>>list.append(‘a’) >>>list.append([333,12.1]) L1.sort() L1.sort() orders a list in-place (ascending order). >>>list.sort() append() and sort() change object in-place. >>>print [1,2,3,4].sort()

List Methods L1.reverse() L1.reverse() reverses the list in-place. >>>list=[1,2,3,4] >>>list.reverse() L1.pop() L1.pop() deletes an item at the end and returns it. >>>list.pop() L1.extend(L2)L2L1 L1.extend(L2) insert items of L2 at the end of L1. >>>list.extend([‘a’,’b’,’c’]) del L1[start], del L1[start:end] del L1[start], del L1[start:end] deletes an item or section. >>>del list[0] >>>del list[2:5]

Dictionaries Most flexible unordered collection of arbitrary objects (numbers, strings, lists) Most flexible unordered collection of arbitrary objects (numbers, strings, lists)  keys to access objects Accessed by key (not offset) Accessed by key (not offset)  Item is fetched by keys associated with set of values. Variable length, heterogeneous, arbitrary nestable Variable length, heterogeneous, arbitrary nestable Mutable mapping Mutable mapping  Don’t support sequence operation like concatenation, slicing. Tables of object references (hash tables) Tables of object references (hash tables) >>>D1={} >>>D1={} # an empty dictionary >>>D2={‘abc’:4, ‘key’:’value’} >>>D3={‘abc’:{‘key’:3,’value’:5}}

Basic Operations Fetch a value by using an associated key. >>>D1={‘abc’:4, ‘key’:’value’,345:’str’} >>>D1[‘abc’],D1[345] len(D1)D1. len(D1) returns number of items in the dictionary D1. >>>len(D1) D1.has_key(key), key1 in D1. D1.has_key(key), key1 in D1 tests for key existence (true/false). >>>D1.has_key(‘abc’),D1.has_key(333) >>>’abc’ in D1,333 in D1 D1.keys() D1. D1.keys() returns list of the keys in the dictionary D1. >>>list=D1.keys()

Changing Dictionaries In-Place Assign value to a key to change or create entry. >>>d1={} >>>d1[‘one’]=23 >>>d1[‘one’]=‘first’ del D1[key1]key1 del D1[key1] deletes entry associated with key1. >>>del d1[‘one’]

Dictionary Methods D1.values()D1 D1.values() returns list of values in D1. D1.items()D1 D1.items() returns (key, value) pairs in D1. >>>D1={‘abc’:4, ‘key’:’value’,345:’str’} >>>D1.values(),D1.items() D1.get(key) D1.get(key) fetches a value by key(None). >>>D1.get(‘abc’), D1.get(3) D1.update(D2) D1.update(D2) merges two dictionaries, blindly overwriting values of the same key. >>>D2={‘abc’:’changed’} >>>D1.update(D2) D1. copy() D1. copy() creates a copy. >>>D2=D1.copy()

Dictionary Example