You are on page 1of 42

M110: Python Programming

Meetings #5_6

Collection Data Types


Lists , Tuples, Dictionaries, Sets

Prepared by Dr. Ahmad Mikati


Contents
• Collections
• Introduction to lists
• List Slicing
• Finding items in lists with the in operator
• List Methods and useful built-in Functions
• Two-dimensional lists
• Tuples
• Dictionaries
• Sets

AOU-M110 2
Introduction
• Python programming language has four collection data types- list, tuple,
sets and dictionary. They have different characteristics based on the
declaration and the usage.
• A sequence is an object that contains multiple items of data. The items
that are in a sequence are stored one after the other.
• Python provides various ways to perform operations on the items that are
stored in a sequence.
• There are several different types of sequence objects in Python.

• In this lecture, we will look at two of the fundamental sequence types: lists
and tuples.
• Both lists and tuples are sequences that can hold various types of data.
• We will explore some of the operations that you may perform on these
sequences, including ways to access and manipulate their contents, in
addition to having a look at some important notes about Dictionaries and
Sets.

AOU-M110 3
Lists
• A list is an object that contains multiple data items.
• Lists are mutable, which means that their contents
can be changed during a program’s execution.
• Lists are dynamic data structures, meaning that
items may be added to them or removed from them.
• You can use indexing, slicing, and various methods
to work with lists in a program.

AOU-M110 4
Lists
• A list is a data structure in Python that is a mutable (or
changeable), ordered sequence of elements.
• Each element or value that is inside of a list is called an item.
• Lists are defined by having values between square brackets [ ].
• Lists are great to use when you want to work with many related values.
• They enable you to keep data together that belongs together, condense
your code, and perform the same methods and operations on multiple
values at once.
• To create a list, we use square brackets to indicate the start and end of
the list and separate the items by commas.
Here is a statement that creates a list of integers:
List1= [1,2,3,4,5]

5
AOU-M110
Lists
List1= [1,2,3,4,5]
• You can use the print function to print the entire contents of a list:
print(List1) #[1, 2, 3,4,5] will be printed

• Lists are mutable: individual elements can be reassigned in place.


List1[0] = 6
print(List1) #[6, 2, 3,4,5] will be printed

• The empty list is []. It is the list equivalent of 0 or empty string ‘’.

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]

6
AOU-M110
Lists
• An example of a list with three integers is [4, 2, -9].
Lists can be assigned to variables, e.g., temperatures= [4, 2,-9].
The variable name should reflect the content of the list to make the
program easier to understand.

There are several things which work the same way for lists as for strings.
• len(): where you can use len(L) to know the number of items in a list L.
• in: operator which tells you if a list contains something.
Examples:
len(temperatures) computes the length of temperatures (3)
if 2 in temperatures:
print('Your list contains number 2.')
if 0 not in temperatures:
print('Your list has no zeroes.')

AOU-M110 7
Lists
Iterating over a List with the for Loop
You can also iterate over a list with the for loop as follows:
1- iterate-by-item
2- iterate-by-position (index)

1- iterate-by-
item:
The for loop is used to iterate over the items of any sequence using in operator

2- iterate-by-position:

The for loop is also used to access elements from a sequence via their position
using built-in function range().
Example: Both of the following examples print out the items of a list
iterate-by-item iterate-by-position
L=[6,7,8,9,10] L=[6,7,8,9,10]
for i in L: for i in range(5):
print(i, end=' ') print(L[i], end=' ')
6 7 8 9 10 6 7 8 9 10
AOU-M110 8
Lists
The Repetition Operator
The repetition operator makes multiple copies of a list and joins them all
together.
Here is the general format: list * n
In the general format, list is a list, and n is the number of copies to make.

Example:

List1= [1,2,3,4,5]
List2=List1*2 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
print(List2)

AOU-M110 9
Lists
Concatenating Lists
To concatenate means to join two things together. You can use the +
operator to concatenate two lists.
Example: list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8]
list3 = list1 + list2
print(list3)

You can also use the += augmented assignment operator to concatenate one
list to another.
Example: list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8]
list1 += list2
print(list1)
N.B: If you try to concatenate a list with something
that is not a list, an exception will be raised.

AOU-M110 10
Lists
Indexing and slicing work exactly as with strings:
L=[5,7,9, 8,10]

Indexing:To retrieve an element of the list, we use the index operator ([]):
L[0] is the first item of the list L. 5
Sometimes, you want to select more than one element from a sequence.
In Python, you can write expressions that select subsections of a sequence, known
as slices.

Slicing: A slice is a subset of list elements that are taken from a sequence.
When you take a slice from a list, you get a span of elements from within
the list.
To get a slice of a list, write the following general format:
list_name[start : stop : step]
The expression returns a list containing a copy of the elements from start up to
(but not including) stop. The step is an integer number specifying the step of the
slicing.

AOU-M110 11
Lists
Examples:

list1 = [1, 2, 3, 4,5,6,7,8]

print(list1[1:4]) [2, 3, 4]

print(list1[:3]) [1, 2, 3]

print(list1[4:]) [5, 6, 7, 8]

print(list1[1:len(list1)]) [2, 3, 4, 5, 6, 7, 8]

print(list1[::2]) [1, 3, 5, 7]

print(list1[-1:-5:-1]) [8, 7, 6, 5]

AOU-M110 12
List Methods and Built-in Functions
Lists have numerous methods that allow you to add elements, remove
elements, change the ordering of elements, and so forth.
Below are some useful methods:
Method Description
append(item) Adds item to the end of the list.
index(item) Returns the index of the first element whose value is
equal to item.

Inserts item into the list at the specified index. When an


item is inserted into a list, the list is expanded in size to
insert(index, item) accommodate the new item. The item that was previously
at the specified index, and all the items after it, are shifted
by one position toward the end of the list.
sort() Sorts the items in the list so they appear in ascending
order (from the lowest value to the highest value).
remove(item) Removes the first occurrence of item from the list.
reverse() Reverses the order of the items in the list.
count (item) returns the number of occurrences of item in the list
pop(index) removes the item at the specified index and returns its
value

AOU-M110 13
List Methods and Built-in Functions
Examples:

L1 = [0,3,2] alist=[10,12,15,16,12,13]
L1.append(1) [0, 3, 2, 1] alist.remove(12) [10, 15, 16, 12, 13]
print(L1) print(alist)

L1 = [0,3,2] 1 alist=[10,12,15,16,12,13]
print(L1.index(3)) alist.reverse() [13, 12, 16, 15, 12, 10]
print(alist)
L1 = [0,3,2]
L1.insert(2,4) [0, 3, 4, 2] alist=[10,12,15,16,12,13] 2
print(L1) print(alist.count(12))

alist=[10,12,15,16,12,13]
L1 = [0,3,2] [10, 12, 16, 12, 13]
L1.sort() [0, 2, 3] alist.pop(2)
print(alist)
print(L1)

AOU-M110 14
List Methods and Built-in Functions
There are several built-in functions that operate on lists.

Below are some useful functions

Function Description
len Returns the number of items in the list
sum Returns the sum of the items in the list
min Returns the minimum of the items in the list
max Returns the maximum of the items in the list

For example, the following computes the average of the values in the list L:

L=[5,7,9, 8,10]
average= sum(L)/len(L) 7.8
print(average)

AOU-M110 15
Two-Dimensional Lists (Lists of Lists)
A two-dimensional list is a list that has other lists as its elements.
Lists of lists are also known as nested lists, or two-dimensional lists.
It is common to think of a two-dimensional list as having rows and columns of
elements
Example:
List=[['Ali', 5, 10,15],['Naji',12,12,15],['Fadi',10,14,12],['Rajaa',18,16,14]]

List is a list of lists. Each item in this list is a list that is composed of ,say,
name and three grades.
List[1] will report ['Naji', 12, 12, 15]
List[0][0] will report Ali
List[2][2] will report 14

AOU-M110 16
List of lists Example
• Suppose we have the following list:
List=[['Ali', 5, 10,15],['Naji',12,12,15],['Fadi',10,14,12],['Rajaa',18,16,14]]
- Print the average of the second grade for all students.

This is not the


function sum!
Why can’t we
use the sum Accessing the 2nd grade
function here?

- Print the name of the student and his/her average grade

OR

AOU-M110 17
Tuples
A tuple is a sequence, very much like a list. The primary difference between tuples
and lists is that tuples are immutable. That means once a tuple is created, it cannot
be changed.
When you create a tuple, you enclose its elements in a set of parentheses, as shown
in the following example:
my_tuple = (1, 2, 3, 4, 5) (1, 2, 3, 4, 5)
print(my_tuple)
Initialize a Tuple
There are two ways to initialize an empty tuple.
• You can initialize an empty tuple by having () with no values in them.
my_Tuple = ()
• You can also initialize an empty tuple by using the tuple function.
my_Tuple = tuple()

AOU-M110 18
Tuples
Iteration by item :
The following example shows how a for loop can iterate by the items in a tuple:
my_tuple = (1, 2, 3, 4, 5)
for item in my_tuple: 12345
print(item, end=' ')

Iteration by index:

The following example shows how a for loop can iterate by the index in a tuple:

my_tuple = (1, 2, 3, 4, 5)
for i in range(len(my_tuple)): 12345
print(my_tuple[i], end=' ')

AOU-M110 19
Tuples
• Tuples support all the same operations as lists, except those that change the
contents of the list.
• Tuples support the following:
• Subscript indexing (for retrieving element values only)
• Methods such as index()
• Built-in functions such as len(), min(), and max()
• Slicing expressions
• The in operator
• The + and * operators

• Tuples do not support methods such as append(), remove(), insert(),


reverse(), and sort().

NOTE: If you want to create a tuple with just one element, you must write a trailing comma
after the element’s value, otherwise Python will not recognize it as a tuple.
my_tuple = (1,) # Creates a tuple with one element.

AOU-M110 20
Tuples
You might wonder why tuples exist, if the only difference between lists and tuples
is immutability!
One reason that tuples exist is performance- faster than processing a list
Another reason is that tuples are safe- not allowed to change the contents of a tuple
Converting Between Lists and Tuples
You can use the built-in list() function to convert a tuple to a list, and the built-in
tuple() function to convert a list to a tuple.

my_tuple = (1, 2, 3, 4, 5)
my_list= list(my_tuple) [1, 2, 3, 4, 5]
print(my_list)

list1=['Ali', 'Mazen', 'Nawaf'] ('Ali', 'Mazen', 'Nawaf')


tuple1= tuple(list1)
print(tuple1)

AOU-M110 21
Tuples
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are immutable.

But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.

x = ("apple", "banana", "cherry")


y = list(x) ('apple', 'kiwi', 'cherry')
y[1] = "kiwi"
x = tuple(y)
print(x)

AOU-M110 22
Tuples
Add Items
Since tuples are immutable, they do not have a build-in append() method, but
there are other ways to add items to a tuple.

a) Convert into a list: Just like the workaround for changing a tuple, you can
convert it into a list, add your item(s), and convert it back into a tuple.
my_tuple = ("apple", "banana", "cherry")
y = list(my_tuple) ('apple', 'banana', 'cherry', 'orange')
y.append("orange")
my_tuple = tuple(y)
print(my_tuple)

b) Add tuple to a tuple.


my_tuple = ("apple", "banana", "cherry")
y = ("orange",) ('apple', 'banana', 'cherry', 'orange')
my_tuple += y
print(my_tuple)

AOU-M110 23
Dictionaries
When you hear the word “dictionary,” you probably think about a large book
containing words and their definitions. If you want to know the meaning of a
particular word, you locate it in the dictionary to find its definition.

In Python, a dictionary is an object that stores a collection of data. Each element


that is stored in a dictionary has two parts: a key and a value. Key-value pairs are
often referred to as mappings because each key is mapped to a value.

In fact, dictionary elements are commonly referred to as key-value pairs. When


you want to retrieve a specific value from a dictionary, you use the key that is
associated with that value.

An example would be a program that lets us enter a person’s name and gives us
that person’s phone number. The program could use a dictionary in which each
element contains a person’s name as the key, and that person’s phone number as
the value. If we know a person’s name, then we can retrieve that person’s phone
number.

AOU-M110 24
Creating a Dictionary
You can create a dictionary by enclosing the elements inside a set of curly braces {}.
An element consists of a key, followed by a colon :, followed by a value.
The elements are separated by commas.

phonebook = {'Jamil':'963−11112222', 'Fadia':'692−43219876', 'Mazen':'961−3665169'}

In the above example, the keys and the values are strings. The values in a dictionary
can be objects of any type, but the keys must be immutable objects.
For example, keys can be strings, integers, floating-point values, or tuples.
Keys cannot be lists or any other type of mutable objects.

Dictionaries themselves are mutable, so entries can be added, removed, and changed
at any time.
Note, though, that because entries are accessed by their key, we can't have two
entries with the same key.

AOU-M110 25
Retrieving a Value from a Dictionary
The elements in a dictionary are not stored in any particular order. For example,
look at the following interactive session in which a dictionary is created, and its
elements are displayed:

Notice the order in which the elements are displayed is different than the order in
which they were created.

This illustrates how dictionaries are not sequences, like lists, tuples, and strings.
As a result, you cannot use a numeric index to retrieve a value by its position from a
dictionary.
Instead, you use a key to retrieve a value.

AOU-M110 26
Retrieving a Value from a Dictionary
To retrieve a value from a dictionary, you simply write an expression in the
following general format:
dictionary_name[key]

In the general format, dictionary_name is the variable that references the dictionary,
and key is a key.
If the key exists in the dictionary, the expression returns the value that is
associated with the key. If the key does not exist, a KeyError exception is raised.

AOU-M110 27
Using the in and not in Operators to Test
for a Value in a Dictionary
As previously demonstrated, a KeyError exception is raised if you try to retrieve
a value from a dictionary using a nonexistent key.
To prevent such an exception, you can use the in operator to determine whether a
key exists before you try to use it to retrieve a value.
You can also use the not in operator to determine whether a key does not exist.

N.B: Keep in mind that string comparisons with the in and not in operators are case sensitive!
AOU-M110 28
Adding Elements to a Dictionary
You can add a key-value pair to a dictionary using a new index key and assigning
a value to it:

# adding to/updating a dictionary


phonebook = {'Jamil':'963−11112222', 'Fadia':'692−43219876', 'Mazen':'961−3665169'}
phonebook['Jamal']='961-76411262'
phonebook['Fadia']='962-43219875’
print(phonebook)

{'Jamil': '963−11112222', 'Fadia': '962-43219875', 'Mazen': '961−3665169', 'Jamal':


'961-76411262'}

AOU-M110 29
Deleting Elements from a Dictionary
You can delete an existing key-value pair from a dictionary with the del
statement. Below is the general format:
del dictionary_name[key]

After the statement executes, the key and its associated value will be deleted
from the dictionary. If the key does not exist, a KeyError exception is raised.

phonebook = {'Jamil':'963−11112222', 'Fadia':'692−43219876', 'Mazen':'961−3665169'}


del phonebook['Fadia’]
print(phonebook)

{'Jamil': '963−11112222', 'Mazen': '961−3665169'}

AOU-M110 30
More about Dictionaries
Finding the Number of Elements in a Dictionary
You can use the built-in len() function to get the number of elements in a dictionary.

phonebook = {'Jamil':'963−11112222', 'Fadia':'692−43219876', 'Mazen':'961−3665169'}


print(len(phonebook)) 3

Creating an Empty Dictionary


You can use an empty set of curly braces to create an empty dictionary {}.
phonebook = {}
Mixing Data Types in a Dictionary
The keys in a dictionary must be immutable objects, but their associated values can
be any type of object. The keys can be of different types, too, as long as they
are immutable.
Key types: string, integer, tuple

mixed_types = {‘dani':1, 2022:”Elections”, (1, 2, 3):[3, 6, 9]}


Value types: integer, string,
list AOU-M110 31
Useful Dictionary Methods/Functions
Method Description
clear Clears the contents of a dictionary.
Gets the value associated with a specified key. If the key is not found, the method
get
does not raise an exception. Instead, it returns a default value.
Returns all the keys in a dictionary and their associated values as a sequence of
items
tuples.
keys Returns all the keys in a dictionary as a sequence of tuples.

Returns the value associated with a specified key and removes that key-value pair
pop
from the dictionary. If the key is not found, the method returns a default value.

Returns a randomly selected key-value pair as a tuple from the dictionary and
popitem
removes that key-value pair from the dictionary.
values Returns all the values in the dictionary as a sequence of tuples.

Function Description
in returns True iff the dictionary contains an entry with the tested key
len returns the number of elements in a dictionary

AOU-M110 32
Sets
A set is an object that stores a collection of data in the same way as
mathematical sets.

There are some aspects that you should know about sets:
 All the elements in a set must be unique. No two elements can have the
same value.
 Sets are unordered, which means that the elements in a set are not stored in
any order.
 Stored elements in a set can be of different data types.

AOU-M110 33
Sets
Creating a Set
To create a set, you need to call the built-in set function.
For example, my_set = set() to create an empty set;

The argument that you pass must be an object that contains iterable elements,
such as a list, a tuple, or a string.
The individual elements of the object that you pass as an argument become
elements of the set.
set1=set(['x', 'y', 'z']) {'y', 'x', 'z'} a set containing the elements ‘x', ‘y', and ‘z'.
print(set1)

set2=set('ahmad') {'a', 'h', 'm', 'd'} Sets cannot contain duplicate elements.
print(set2)

What if you want to create a set in which each element


is a string containing more than one character?

AOU-M110 34
Sets
Creating a Set
If you want to create a set in which each element is a string containing more
than one character, you should pass a list containing the strings.

AOU-M110 35
Sets
Adding, updating, and Removing Elements
Sets are mutable objects, so you can add items to them, update the sets, and remove
items from them.
You use the add() method to add an element to a set.
You can add a group of elements to a set all at one time with the update() method.
You can remove an item from a set with either the remove() method or the discard()
method.

AOU-M110 36
Sets
Finding the Union and Intersection of Sets
The union of two sets is a set that contains all the elements of both sets, while the
intersection of two sets is a set that contains only the elements that are found in both
sets.

In Python, you can call the union() method (or |) to get the union of two sets.
Moreover, you can call the intersection() method to get the intersection of two sets.

or

AOU-M110 37
Sets
Finding the Difference and Symmetric Difference of Sets
The difference of set1 and set2 is the elements that appear in set1 but do not appear
in set2, while the symmetric difference of two sets is a set that contains the elements
that are not shared by the sets.

You can call the difference() method (or -)to get the difference of two sets.
You can call the symmetric_difference() method (or ^)to get the symmetric difference
of two sets.

or

or

AOU-M110 38
Sets
Finding Subsets and Supersets
In Python, you can call the issubset() method (or <=) to determine whether one set
is a subset of another. The method returns True if set2 is a subset of set1. Otherwise,
it returns False.
Also, you can call the issuperset() method (or >=) to determine whether one set is a
superset of another. The method returns True if set1 is a superset of set2.

AOU-M110 39
Extra Exercises
1. Find the second largest element in a list of integers
2. Find the nth largest element in a list of integers
3. Given a list of integers, find the first number that is divisible by 3
4. Given a list of strings, count the number of strings that are longer
than 5 characters.
5. Given a list of strings, find the longest string in the list.
6. Write a program that takes in a list of numbers and finds the largest
prime number in the list.
7. Given a list of tuples, find the average of the second elements of all
the tuples.

AOU-M110
Extra Exercises
8. Write a program that takes in a list of integers and removes all duplicates, then
prints the resulting list. (Hint: Use Sets)
9. Write a program that takes in two lists of integers and returns a set containing
only the elements that appear in both lists. (Hint: Use Sets)
10. Write a program that takes in a list of tuples representing (name, age) pairs, and
returns a dictionary with the names as keys and ages as values.
11. Write a program that takes in a list of strings and returns a dictionary containing
the frequency of each word in the list.
12. Write a program that takes in a list of tuples representing (name, score) pairs,
and returns a dictionary with the names as keys and the average score as values.
13. Write a program that takes in a list of tuples representing (item, price) pairs, and
returns a dictionary with the items as keys and the total price for each item as
values.

AOU-M110
Summary
This lecture covered:
Lists, including:
• Repetition and concatenation operators
• Indexing
• Techniques for processing lists
• Slicing and copying lists
• List methods and built-in functions for lists
• Two-dimensional lists
Tuples, including:
• Immutability
• Difference from and advantages over lists
Dictionaries, including:
• Creating dictionaries
• Inserting, retrieving, adding, and deleting key-value pairs
• Dictionary methods

Sets, including:
• Creating sets
• Adding elements to and removing elements from sets
• Finding set union, intersection, difference and symmetric difference
• Finding subsets and supersets

AOU-M110 42

You might also like