CMPT 120 - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

CMPT 120

Description:

Understand and use lists, tuples and dictionaries. Define the term sequence ... scary = ('bats', 'ghouls', 'Celine Dion') October 2004. 4. John Edgar. Creating Tuples ... – PowerPoint PPT presentation

Number of Views:108
Avg rating:3.0/5.0
Slides: 32
Provided by: johne78
Category:
Tags: cmpt | celine | dion

less

Transcript and Presenter's Notes

Title: CMPT 120


1
CMPT 120
  • Sequences Strings, Tuples, Lists and Dictionaries

2
Objectives
  • Understand and use lists, tuples and dictionaries
  • Define the term sequence
  • Use index notation with sequences
  • Use slice notation with sequences

3
Tuples
  • A tuple is an immutable, ordered sequence of
    objects
  • Immutable means unchangeable
  • Ordered means that the order of the objects
    matters
  • Tuples are written as a list of objects
  • Tuples begin with a ( and end with a )
  • Items in a tuple are separated by commas, below
    is a tuple consisting of strings
  • scary ('bats', 'ghouls', 'Celine Dion')

4
Creating Tuples
  • Tuples can contain different types of objects
  • For example, consider a tuple to represent a
    student, we might want to record the students
    name (first and last), age and GPA
  • Thats two strings, an integer and a float
  • s1 ('Bruce', 'Wayne', 19, 4.33)
  • Note that tuples can be created using variables
    in the place of values

5
Creating a Student Tuple
  • def create_student()
  • f_name raw_input("What is your first name? ")
  • l_name raw_input("What is your last name? ")
  • mature raw_input("Are you a mature student? ")
  • age raw_input("What is your age? ")
  • if mature "y"
  • age raw_input(" No, what is your REAL age? ")
  • This next line may not be a good way to get
  • this data!!
  • gpa raw_input("What is your GPA (be honest)?
    ")
  • return(f_name, l_name, int(age), float(gpa))

6
Creating Small Tuples
  • Python interprets ( and ) as if they were
    brackets in an arithmetic expression unless it is
    clear that they refer to a tuple
  • monster ('zombie', 'werewolf') is a tuple
  • monster ('zombie') could be a (rather
    pointless) ordinary use of brackets
  • To create a tuple containing a single object add
    a trailing comma
  • monster ('zombie', )

7
Manipulating Tuples
  • The and operators can be used with tuples in
    the same way that they can with strings
  • concatenates tuples
  • repeats tuples
  • Note that using these operators creates a new
    tuple rather than changing the old one, e.g.
  • undead ('skeleton', 'zombie')
  • undead undead ('ghost', )

8
Hang On
  • In undead undead ('ghost', ) it looks as if
    we might be changing a tuple
  • But tuples are immutable
  • So what is happening here?
  • Variables are not containers of objects but are
    pointers or references to objects
  • Think of a variable as a signpost rather than a
    box
  • In the example above we make a new tuple and then
    make the variable undead point to it

9
More Tuple Operations
  • The len function returns the number of objects in
    a tuple
  • Tuples can be used in for loops in the same way
    as any other sequence
  • To assign each member of the veg tuple to plant
    in turn and print it
  • gtgtgt veg ('cabbage', 'yam', 'eggplant')
  • gtgtgt for plant in veg
  • print plant

10
Membership Operator - in
  • The keyword in can be used to test whether or not
    an object is in (i.e. is a member of) a tuple
  • in is a boolean operator (returns True or False)
  • gtgtgt veg ('cabbage', 'yam', 'eggplant')
  • gtgtgt 'tomato' in veg would return
  • False
  • not can be be combined with in to see if an
    object is not a member of a tuple

11
Lists
  • Lists are one of the most important data
    structures in any programming language
  • In Python a list is a mutable (i.e. changeable)
    ordered sequence of objects
  • Remember that strings and tuples cannot be
    changed, but
  • A list can be changed parts of a list can be
    modified or re-ordered in all sorts of useful ways

12
Creating Lists
  • Lists are created in a similar way to tuples
  • Lists begin with a and end with a
  • Items in a list are separated by commas
  • Lists can contain any type of objects, even
    tuples and other lists
  • instructor_120 'Toby', 'John', 'Wing'
  • Unlike tuples small (i.e. one object long) lists
    can be created without a trailing comma
  • instructor_225 'John' creates a small list

13
Making a List of Tuples
  • The following code would create a list of student
    tuples
  • gtgtgt st1 ('Clark', 'Kent', 23, 3.5)
  • gtgtgt st2 ('Diana', 'Troy', 23, 3.5)
  • gtgtgt st3 ('Carol', 'Danvers', 23, 3.5)
  • gtgtgt student st1, st2, st3

14
The range function
  • The range function returns a list of integers
  • The function takes one, two or three arguments
  • The arguments specify the start of the range, one
    past the end of the range, and the step distance
  • range(0, 18, 3) returns 0, 3, 6, 9, 12, 15
  • When two arguments are given they represent the
    start and one past the end of the range. The
    step distance is 1
  • If one argument is give it represents the one
    past the end of the range. The range start at 0
    and the step distance is 1

15
List Operations
  • Unlike tuples and strings, lists can be modified,
    and there are useful functions to help do this
  • Use dir() to see all the available methods
  • Here are a few of them (where L is a list)
  • L.sort() sorts the list in ascending order
  • L.reverse() reverses the order of the items of
    L
  • L.insert(i, x) inserts object x just before
    index i
  • L.remove(x) removes the first item x from L
  • L.append(x) adds the item x to the end of L

16
Sequences
  • A sequence is an ordered set of elements, where
    each element is identified by an index
  • Strings, tuples and lists are all types of
    sequences
  • Strings are sequences of characters
  • Tuples and lists are sequences of any object
  • Strings and tuples are immutable and lists are
    mutable
  • There are a number of operations that work the
    same for strings, tuples and lists

17
Sequence Operations
  • len(S) returns the number of objects in sequence
    S
  • S T returns a new sequence consisting of the
    objects in S followed by the objects in T
  • S and T must be sequences of the same type (e.g.
    both lists, or both strings, not a list and a
    string)
  • n S returns a new sequence consisting of n
    copies of S, if n lt 0 an empty sequence is
    returned

18
More Sequence Operations
  • x in S returns True if and only if x is in the
    sequence S, otherwise returns False
  • x not in S returns True if and only if x is not
    in the sequence S, otherwise returns False
  • for x in S iterates through S len(S) times, each
    time assigning the next item in S to x (starting
    with the first)
  • There are other built-in functions that work on
    sequences (e.g. min and max)

19
Sequence Indexing
  • Sequences are indexed
  • Each item of a sequence can be accessed by its
    position in the sequence
  • The index is written in s
  • If the variable drac 'Vlad the Impaler'
  • then drac0 is 'V', drac2 is 'a' and so on
  • Python uses zero based indexing, where the first
    index is 0 and the last is n-1 (where n is the
    number of objects in the sequence)

20
Negative Indexing
  • Python allows sequence elements to be easily
    accessed from the end, without knowing how many
    elements the sequence contains
  • The last item is given the index -1, the second
    to last -2 and so on
  • So the indexes (or indices) of drac would be

21
Lists and Indexing
  • Unlike tuples and strings, lists are mutable
  • Individual elements can be modified by accessing
    them directly using an index
  • gtgtgt lst 13, 666, 42
  • gtgtgt lst1 'Happy Bunny'
  • gtgtgt lst
  • 13, 'Happy Bunny', 42
  • Trying to do the same thing with a string or a
    tuple will result in an error

22
Lists and Variables
  • How many lists are there?
  • gtgtgt lst 11, 79, 121
  • gtgtgt other_lst lst
  • There is only one list, but two variables refer
    to it
  • Be careful when changing lists, in the example
    given above it may be appropriate to make an
    actual copy of the list before changing it
  • gtgtgt other_lst lst

23
Sequence Slices
  • Slicing returns a copy of part of a sequence
  • A slice is specified by the list name followed by
    ij where i is the start of the slice and j is
    one item past the end of the slice
  • If only the starting index is given the slice
    goes to the end of the sequence
  • If only the ending index is given the slice
    starts from the start of the sequence (index 0)
  • The slice returns a copy of the entire
    sequence

24
Slicing
  • The first index is the start of the slice, and
    the second is one past the end of the slice
  • gtgtgt lst 1, 3, 5, 7, 9, 13, 15
  • gtgtgt lst13
  • 3, 5
  • gtgtgt lst3
  • 7, 9, 13, 15
  • gtgtgt lst6
  • 1, 3, 5, 7, 9, 13

25
More List Operations
  • Now that weve seen indexing and slicing lets
    introduce two more list operations
  • del Li removes the object at index i from L
  • del Lij removes the given slice from L
  • Both these operations affect L, they do not
    return a copy of the list
  • Note that entire slices of lists can be
    re-assigned in the same way that individual items
    can be

26
Indexing (again)
  • As weve seen lists and tuples (and strings) can
    be indexed
  • lsti accesses the ith item in the list
  • The index must be an integer value between 0 and
    1 less than the size of the list
  • However, it is often necessary to look up one
    value, using another, related, value
  • e.g. looking up the meaning of a word, or looking
    up a students GPA,

27
Dictionaries
  • Lets say we want to create a Latin to English
    dictionary to look up the English meanings of
    Latin words
  • Knowing the position (index 0, 1, 2, ) of either
    word really doesnt help very much
  • The dictionary data structure can be used to
    store and look up a value given a particular key
  • The key acts as an index for the value

28
Python Dictionaries
  • A dictionary consists of a curly brackets, ,
    containing a sequence of comma separated pairs
  • The members of each pair are separated by colons
  • To create a dictionary either enter a list of
    key-value pairs
  • antonyms 'in' 'out', 'big' 'small', 'first'
    'second', 'right' 'wrong'
  • or
  • Start with an empty dictionary and assign each
    value to the appropriate index, using the desired
    key as the index

29
Creating a Dictionary
  • Heres an example that creates a (very small)
    Latin English dictionary
  • gtgtgt latin
  • gtgtgt latin'bubo' 'owl'
  • gtgtgt latin'carmen' 'song'
  • gtgtgt latin'fortis' 'strong'
  • gtgtgt latin'onus' 'load'
  • gtgtgt latin
  • 'bubo' 'owl', 'onus' 'load', 'carmen' 'song',
    'fortis' 'strong'

30
Dictionary Operations
  • del dictkey deletes the key-value indexed by
    the given key from the dictionary
  • gtgtgt antonyms
  • 'big' 'small', 'first' 'second', 'right'
    'wrong', 'in' 'out'
  • gtgtgt del antonyms'first'
  • gtgtgt antonyms
  • 'big' 'small', 'right' 'wrong', 'in' 'out'
  • len(dict) returns the number of key-value pairs
    in the dictionary
  • Dictionary values can be accessed, and changed,
    using their keys as an index

31
Dictionary Methods
  • The keys method returns a list of the
    dictionary's keys
  • gtgtgt latin.keys()
  • 'bubo', 'onus', 'carmen', 'fortis'
  • The values method returns a list of the values
  • gtgtgt latin.values()
  • 'owl', 'load', 'song', 'strong'
  • The has_key method returns True if the given key
    is contained in the dictionary and False
    otherwise
  • gtgtgt latin.has_key('onus')
  • True
  • Use dir() to review all of the dictionary
    methods
Write a Comment
User Comments (0)
About PowerShow.com