Lesson 13 Slides
Lesson 13 Slides
Lesson 13
Sequences and dictionaries
SEDIN
IT Education Services Center
2
Sequences
• Sequences are objects that hold multiple items of data, stored one after the
other
• There are different types of sequences, including strings, lists and tuples
• Although they have different characteristics, sequences:
- are iterable objects
- can be mutable or immutable
- the position of each value is identified by a number (index)
- use many functions, methods and operations that allow you to access and
work on the data
4
Mutability of sequences
Sequences
IMMUTABLE MUTABLE
Strings Lists
Tuples
5
Strings
• A string is a sequence of characters that can contain alphanumeric
characters and symbols
• Strings are immutable, so we cannot change an existing string, but it’s
possible to create a new string that is a variation on the original
Example:
>>> univ = 'Bocconi’
>>> univ = 'UniBocconi'
6
Lists
• A list is a sequence of values (elements) of any type, enclosed in square brackets
and divided by commas:
[19, 30, 24, 28] ['Bocconi', 'IULM', 'Bicocca’] [156, 'Via Roma', 'Milano’, 3318488888, 15.36]
Tuples
• A tuple is sequence very similar to a list. The elements of a tuple can be of any type, are
comma-separated and enclosed in a set of parentheses :
>>> t = ('b', 'o', 'c', 'c', 'o', 'n', 'i’)
• Although not necessary, it is common to enclose tuples in parentheses
• To create a tuple we can use the built-in function tuple
• Tuples are immutable, so it is not possible to modify an existing tuple: the only possibility
is to create a new tuple, variant of the original.
8
Indexing
• The position of each element within a sequence is identified by an integer, called an index
• Indexing allows access to the individual elements of a sequence, using the following syntax:
sequence[index]
• The index of the first element on the left is equal to 0, while the index of the last element of
the sequence is equal to the number of elements of the sequence minus 1.
• It is possible to use indices with negative values: in this case the count starts from the end
of the sequence
10
Slicing
• A segment or portion of a sequence is called a slice
• Slicing allows to select more than one element of a sequence using the
syntax: sequence[start:end:step]
• The operation returns all the elements of the sequence from the one with the
start index (included) and the one with the end index (not included). Step is
optional and indicates which subsequent indexes to select after the first one
11
Examples of slicing
• When start is omitted, the slicing selects the elements starting from the first one; when end
is omitted, the slicing selects the elements up to the last one. By omitting both, the entire
sequence is selected
• Consider the string 'Computer viruses are an urban legend' stored in the variable quote. Here
are some examples of slicing:
Methods
• Strings, lists and tuples have special functions, called methods
• The syntax of functions requires that the sequence or the name of the
variable in which it is stored is one of the arguments of the function
• The syntax of methods requires that the name of the sequence is always
specified, using the following syntax:
object.method(arguments)
13
Methods of strings
Method Description
.upper() Returns a copy of the string with all alphabetic letters converted to uppercase.
Any character that is already uppercase is not modified
.lower() Returns a copy of the string with all alphabetic letters converted to lowercase.
Any character that is already lowercase, is not modified
.find(sub) Search in the string for the substring specified in the sub argument and returns
the index of the first occurrence found
.startswith(prefix) Returns True if the string starts with the string specified in the prefix argument,
otherwise it returns False
.endswith(suffix) Returns True if the string ends with the string specified in the suffix argument,
otherwise it returns False
.count(sub) Returns the number of occurrences of the substring sub in the string
.split(iterable) Splits a string in words and returns a list of strings, considering the space
character as the separator between the words
.join(iterable) Returns a string obtained concatenating all the elements of an iterable object
containing only strings
14
Methods of lists
Method Description
.append(element) Appends new elements to the list
.insert(index, element) Inserts the desired element in the position specified by the index
parameter
.remove(element) Searches for the specified element in the list and removes the first
occurrence
.pop([index]) Removes and returns the element with the specified index. If we
omit the index, it removes the last element of the list
.index(element) Searches for the specified element within the list and returns its
index
.count(element) Counts how many times a given element is found in the list
.sort() Sorts the elements of the list in ascending order
.reverse() Reverses the order of the elements of the list
15
Methods of tuples
• The tuple methods are few because tuples are immutable
• It is often useful to convert a tuple into a list, work on the elements of the list
and then convert it back into a tuple
Method Description
.index(element) Searches for the specified element within the tuple and returns its
index. If the element occurs more than one time, it returns the
index of the first occurrence
.count(element) Returns the number of occurrences of a specified element in a
tuple
16
Dictionaries
• In Python, a dictionary is an object that contains a collection of data or items
• Element are made of two parts: a key and a value. The keys are unique and can be
any kind of immutable objects. Values can be any kind of object, mutable or
immutable.
• To create a dictionary it is necessary to write in curly brackets { } the elements
divided by commas (,). Every element is made of a key followed by a colon (:) and a
value
• Alternatively you can use the dict function, which creates a new dictionary with no
elements
• Dictionaries are mutable objects
17
dict_name[key]
dict_name[key] = value
18
Methods of dictionaries
Method Description
.get(key[,default]) Returns the value associated with the key specified in the key argument. If the
specified key is not found in the dictionary, it returns the value None or the value
specified in the default argument
.pop(key[,default]) Removes the key (and the associated value) specified in the key argument and
returns the associated value. If the specified key is not found in the dictionary and
a default value has not been set in the default argument, it returns a KeyError
error
.popitem() Removes the last key-value pair added to the dictionary and returns a tuple with
two elements (the key and the value removed)
.items() Creates a dict_items object consisting in a list of tuples, each one with two
elements (the key-value pairs)
.keys() Creates a dict_keys object consisting in a list in which each element is one of the
keys of the dictionary
.values() Creates a dict_values object consisting in a list in which each element is one of
the values of the dictionary
20
Traversing dictionaries
• The keys of a dictionary can be traversed using a for loop:
• We can also traverse key-value pairs using the for loop of the list dict.items()
Book references
Learning Python:
Chapters 8, 9
Assignment:
Exercises of lesson 13