0% found this document useful (0 votes)
21 views59 pages

Introduction To Programming 2 - Python - Week 3

This document is a lecture on Python programming, focusing on data structures such as lists, tuples, sets, and dictionaries. It covers their creation, methods, and differences, emphasizing the mutable nature of lists compared to the immutable nature of tuples. Additionally, it introduces the matplotlib library for plotting data and provides installation instructions and examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views59 pages

Introduction To Programming 2 - Python - Week 3

This document is a lecture on Python programming, focusing on data structures such as lists, tuples, sets, and dictionaries. It covers their creation, methods, and differences, emphasizing the mutable nature of lists compared to the immutable nature of tuples. Additionally, it introduces the matplotlib library for plotting data and provides installation instructions and examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction To Programming 2

Python

Lecture 3

Department of Computer Engineering

Astana IT University

Zamart Ramazanova
Senior-Lecturer
[Link]@[Link]

December 2024
Topics
• Lists: Functions and Methods for Lists
• Tuples: Functions and Methods for Tuples
• Sets
• Dictionaries: Functions and Methods for Dictionaries
• Difference between List, Tuple, Set, and Dictionary

2
Sequences
• Sequence: an object that contains
multiple items of data
• The items are stored in sequence one after
another
• Python provides different types of
sequences, including lists and tuples
• The difference between these is that a list is
mutable and a tuple is immutable

3
Copyright © 2018 Pearson Education, Inc.
Introduction to Lists
• List: an object that contains multiple data
items
• Element: An item in a list
• Format: list = [item1, item2, etc.]
• Creating a sample list L: L = [1, 2, 3]
• Can hold items of different types
• print function can be used to display an
entire list
• list() function can convert certain types of
objects to lists
4
Copyright © 2018 Pearson Education, Inc.
Introduction to Lists (cont’d.)

5
Copyright © 2018 Pearson Education, Inc.
Creating Lists
Lists can be created with the l i s t class constructor or
using special syntax.
>>> l i s t ( ) # c r e a t e e mpt y l i s t , wi t h c ons t r uc t or
[]
> > > l i s t ( [ 1 , 2 , 3] ) # c r e a t e l i s t [ 1 , 2 , 3]
[ 1 , 2 , 3]
>>> l i s t ( [ " red " , 3 , 2 . 5 ] ) # c r e a t e heterogeneous l i s t
[ ’ r e d’ , 3 , 2 . 5 ]
> > > [ " r e d" , 3 , 2 . 5 ] # c r e a t e l i s t , no e x p l i c i t c o n s t r u c t o r
[ ’ r e d’ , 3 , 2 . 5 ]
> > > r a nge ( 4) # not an a c t u a l l i s t
r a nge ( 0 , 4)
> > > l i s t ( r a nge ( 4) ) # c r e a t e l i s t u s i n g range
[ 0 , 1 , 2 , 3]
# c r e a t e c h a r a c t e r l i s t from s t r i n g
> > > l i s t ( " a bc d " )
[ ’ a ’ , ’ b ’ , ’ c ’ , ’d ’ ]

6
Copyright © 2018 Pearson Education, Inc.
Indexing
• Index: a number specifying the position
of an element in a list
• Enables access to individual element in list
• Index of first element in the list is 0, second
element is 1, and n’th element is n-1
• Negative indexes identify positions relative to
the end of the list
• The index -1 identifies the last element, -2
identifies the next to last element, etc.

7
Copyright © 2018 Pearson Education, Inc.
Lists
The l i s t class is a very useful tool in Python.

Both lists and strings are sequence types in Python, so


share many similar methods. Unlike strings, lists are
mutable.
If you change a list, it doesn’t create a new copy; it
changes the actual contents of the list. 8
Copyright © 2018 Pearson Education, Inc.
Lists vs. Arrays
Many programming languages have an array type.

Arrays are: Python lists are:


 homogeneous (all elements  heterogeneous (can contain
are of the same type) elements of different types)
 fixed size  variable size
 permit very fast access time  permit fast access time

Lists and arrays are examples of data structures. A very simple definition of
a data structure is a variable that stores other variables.
CS313e explores many standard data structures. 9
Copyright © 2018 Pearson Education, Inc.
The len function
• An IndexError exception is raised if an
invalid index is used
• len function: returns the length of a
sequence such as a list
• Example: size = len(my_list)
• Returns the number of elements in the list, so the
index of last element is len(list)-1
• Can be used to prevent an IndexError exception
when iterating over a list with a loop

10
Copyright © 2018 Pearson Education, Inc.
The len function Example
Suppose you have 30 different test grades to average. You could use
30 variables: grade1, grade2, ..., grade30. Or you could use one list
with 30 elements: grades[0], grades[1], ..., grades[29].

11
Copyright © 2018 Pearson Education, Inc.
Lists Are Mutable
• Mutable sequence: the items in the sequence
can be changed
• Lists are mutable, and so their elements can be
changed
• An expression such as
• list[1] = new_value can be used to
assign a new value to a list element
• Must use a valid index to prevent raising of an
IndexError exception

12
Copyright © 2018 Pearson Education, Inc.
List Slicing
• Slice: a span of items that are taken from a
sequence
• List slicing format: list[start : end]
• Span is a list containing copies of elements from
start up to, but not including, end
• If start not specified, 0 is used for start index
• If end not specified, len(list) is used for end index
• Slicing expressions can include a step value and
negative indexes relative to end of list

13
Copyright © 2018 Pearson Education, Inc.
List Indexing and Slicing
• With Lists you can get sublists using Slicing

14
Copyright © 2018 Pearson Education, Inc.
Finding Items in Lists with the
in Operator
• You can use the in operator to determine
whether an item is contained in a list
• General format: item in list
• Returns True if the item is in the list, or False if it is
not in the list
• Similarly you can use the not in operator to
determine whether an item is not in a list

15
Copyright © 2018 Pearson Education, Inc.
List Methods and Useful Built-
in Functions
• append(item): used to add items to a list –
item is appended to the end of the existing
list
• index(item): used to determine where an
item is located in a list
• Returns the index of the first element in the list
containing item
• Raises ValueError exception if item not in the list

16
Copyright © 2018 Pearson Education, Inc.
List Methods and Useful Built-
in Functions (cont’d.)
• insert(index, item): used to insert
item at position index in the list
• sort(): used to sort the elements of
the list in ascending order
• remove(item): removes the first
occurrence of item in the list
• reverse(): reverses the order of the
elements in the list
17
Copyright © 2018 Pearson Education, Inc.
18
Copyright © 2018 Pearson Education, Inc.
List Methods and Useful Built-
in Functions (cont’d.)
• del statement: removes an element from a
specific index in a list
• General format: del list[i]
• min and max functions: built-in functions
that returns the item that has the lowest or
highest value in a sequence
• The sequence is passed as an argument

19
Copyright © 2018 Pearson Education, Inc.
Copying Lists
• To make a copy of a list you must copy
each element of the list
• Two methods to do this:
• Creating a new empty list and using a for loop to
add a copy of each element from the original list to
the new list
• Creating a new empty list and concatenating the
old list to the new empty list

20
Copyright © 2018 Pearson Education, Inc.
Copying List Example
Make a copy of a list with the copy() method:

Make a copy of a list with the list() method:

21
Copyright © 2018 Pearson Education, Inc.
Tuples
• Tuple: an immutable sequence
• Very similar to a list
• Once it is created it cannot be changed
• Format: tuple_name = (item1, item2)
• Tuples support operations as lists
• Subscript indexing for retrieving elements
• Methods such as index
• Built in functions such as len, min, max
• Slicing expressions
• The in, +, and * operators

22
Copyright © 2018 Pearson Education, Inc.
Tuples (cont’d.)
• Tuples do not support the methods:
• append
• remove
• insert
• reverse
• sort

23
Copyright © 2018 Pearson Education, Inc.
Tuples (cont’d.)
• Advantages for using tuples over lists:
• Processing tuples is faster than processing
lists
• Tuples are safe
• Some operations in Python require use of
tuples
• list() function: converts tuple to list
• tuple() function: converts list to tuple
• The foloowing example converts a list and
a string into tuples:
24
Copyright © 2018 Pearson Education, Inc.
Plotting Data with
matplotlib
• The matplotlib package is a library for
creating two-dimensional charts and graphs.

• It is not part of the standard Python library,


so you will have to install it separately, after
you have installed Python on your system.

25
Copyright © 2018 Pearson Education, Inc.
Plotting Data with
matplotlib
• To install matplotlib on a Windows system, open a
Command Prompt window and enter this command:
pip install matplotlib

• To install matplotlib on a Mac or Linux system,


open a Terminal window and enter this command:
sudo pip3 install matplotlib

• See Appendix F in your textbook for more


information about packages and the pip utility.

26
Copyright © 2018 Pearson Education, Inc.
Plotting Data with
matplotlib
• To verify the package was installed, start IDLE and
enter this command:

>>> import matplotlib

• If you don't see any error messages, you can


assume the package was properly installed.

27
Copyright © 2018 Pearson Education, Inc.
Plotting Data with
matplotlib
• The matplotlib package contains a module
named pyplot that you will need to import.
• Use the following import statement to
import the module and create an alias named
plt:

import [Link] as plt

28
Copyright © 2018 Pearson Education, Inc.
Plotting a Line Graph with the
plot Function
• Use the plot function to create a line graph that
connects a series of points with straight lines.
• The line graph has a horizontal X axis, and a vertical
Y axis.
• Each point in the graph is located at a (X,Y)
coordinate.

29
Copyright © 2018 Pearson Education, Inc.
Let’s Take a Break

30
Copyright © 2018 Pearson Education, Inc.
Plotting a Line Graph with the
plot Function
1 # This program displays a simple line graph.
2 import [Link] as plt
3
4 def main():
5 # Create lists with the X and Y coordinates of each data point.
6 x_coords = [0, 1, 2, 3, 4]
7 y_coords = [0, 3, 1, 5, 2]
8
9 # Build the line graph.
10 [Link](x_coords, y_coords)
11
12 # Display the line graph.
13 [Link]()
14
15 # Call the main function.
16 main()

31
Copyright © 2018 Pearson Education, Inc.
Slicing of Tuple
• Slicing of a Tuple is done to fetch a specific range or slice
of sub-elements from a Tuple.
• Slicing can also be done to lists and arrays.
• Indexing in a list results to fetching a single element
whereas Slicing allows to fetch a set of elements.

32
Copyright © 2018 Pearson Education, Inc.
Slicing of Tuple Example

33
Copyright © 2018 Pearson Education, Inc.
Sets
• Set: object that stores a collection of
data in same way as mathematical set
• All items must be unique
• Set is unordered
• Elements can be of different data types

37 'Python'

['Python', 73, 'CS', 37]


A Set
12.25
34
Copyright © 2018 Pearson Education, Inc.
Creating a Set
• set function: used to create a set
• Simple set creation
• set1 = {12, 'Python', 37, 73}
• For empty set, call set()
• For non-empty set, call set(argument) where
argument is an object that contains iterable
elements
• e.g., argument can be a list, string, or tuple
• If argument is a string, each character becomes a set
element
• For set of strings, pass them to the function as a list
• If argument contains duplicates, only one of the
duplicates will appear in the set 35
Copyright © 2018 Pearson Education, Inc.
Creating Data Types
• List:
• data = [7, 37, 5, 37, 12, 37.5]
• List of lists:
• table = [[1, 2], [3, 7], [19, 73]]
• String:
• name = 'Python Language'
• Tuple:
• tup1 = (37, 'Python', 73, 12, 12)
• Dictionary:
• freq_map = {'Python':3, 'Java':7}
• Set:
• lang_set= {'Python', 'Java', 'C++'}36
Copyright © 2018 Pearson Education, Inc.
Getting the Number of and
Adding Elements
• len function: returns the number of
elements in the set
• Sets are mutable objects
• add method: adds an element to a set
• What if set already contains that element?
• update method: adds a group of
elements to a set
• Argument must be a sequence containing
iterable elements, and each of the elements is
added to the set
37
Copyright © 2018 Pearson Education, Inc.
Deleting Elements From a Set
• remove and discard methods: remove
the specified item from the set
• The item that should be removed is passed to
both methods as an argument
• Behave differently when the specified item is
not found in the set
• remove method raises a KeyError exception
• discard method does not raise an exception
• clear method: clears all the elements
of the set 38
Copyright © 2018 Pearson Education, Inc.
Using the for Loop, in, and
not in Operators With a Set
• A for loop can be used to iterate over
elements in a set
• General format: for item in set:
• The loop iterates once for each element in
the set
• The in operator can be used to test
whether a value exists in a set
• Similarly, the not in operator can be used to
test whether a value does not exist in a set
39
Copyright © 2018 Pearson Education, Inc.
Finding the Union of Sets
• Union of two sets: a set that
contains all the elements of both
sets
• To find the union of two sets:
• Use the union method
• Format: [Link](set2)
• Use the | operator
• Format: set1 | set2
• Both techniques return a new set
which contains the union of both sets
40
Copyright © 2018 Pearson Education, Inc.
Finding the Intersection of Sets
• Intersection of two sets: a set that
contains only the elements found
in both sets
• To find the intersection of two
sets:
• Use the intersection method
• Format: [Link](set2)
• Use the & operator
• Format: set1 & set2
• Both techniques return a new set
which contains the intersection of
both sets 41
Copyright © 2018 Pearson Education, Inc.
Finding the Difference of Sets
• Difference of two sets: a set
that contains the elements
that appear in the first set but set2
do not appear in the second
set
• To find the difference of two
sets:
• Use the difference method
• Format: [Link](set2)
• Use the - operator
• Format: set1 - set2
Copyright © 2018 Pearson Education, Inc.
set1 42
Finding the Symmetric
Difference of Sets
• Symmetric difference of two
sets: a set that contains the
elements that are not shared by
the two sets
• To find the symmetric difference
of two sets:
• Use the symmetric_difference
method
• Format:
set1.symmetric_difference(set2)
• Use the ^ operator
• Format: set1 ^ set2
43
Copyright © 2018 Pearson Education, Inc.
Finding Subsets and
Supersets
• Set A is subset of set B if all the
elements in set A are included in set B
• To determine whether set A is subset of
set B
• Use the issubset method
• Format: [Link](setB)
• Use the <= operator
• Format: setA <= setB

44
Copyright © 2018 Pearson Education, Inc.
Dictionaries
• Dictionary: data structure that stores a
collection of key-value pairs
• Each element consists of a key and a value
• Often referred to as mapping of key to value
• Key must be an immutable object
• A real world dictionary, the words are the keys and the
definitions are the values
• Given the word you can find the value quickly
• To retrieve a specific value, use the key associated
with it
• Format for creating a dictionary with given values
dictionary = {key1:val1, key2:val2}
45
Copyright © 2018 Pearson Education, Inc.
Visualization of Dictionary

• [Link] 46
Copyright © 2018 Pearson Education, Inc.
Adding Elements to an
Existing Dictionary
• Dictionaries are mutable objects
• To add a new key-value pair:
dictionary[key] = value
• If key exists in the dictionary, the value
associated with it will be changed
• if the key doesn't exist this adds the key-value
pair to the dictionary

47
Copyright © 2018 Pearson Education, Inc.
Deleting Elements From an
Existing Dictionary
• To remove a key-value pair:
[Link](key)
• If key is not in the dictionary, KeyError
exception is raised
• OR del dictionary[key]

48
Copyright © 2018 Pearson Education, Inc.
Getting the Number of Elements
and Mixing Data Types
• len function: used to obtain number of
key-value pairs in a dictionary
• Keys must be immutable objects, but
associated values can be any type of
object
• One dictionary can include keys of several
different immutable types. Heterogeneous.
• Values stored in a single dictionary can
be of different types
49
Copyright © 2018 Pearson Education, Inc.
Creating an Empty Dictionary and
Using for Loop to Iterate Over a
Dictionary
• To create an empty dictionary:
• Use {}
• Use built-in function dict()
• Elements can be added to the dictionary as
program executes
• Use a for loop to iterate over a
dictionary
• General format: for key in dictionary:

50
Copyright © 2018 Pearson Education, Inc.
Some Dictionary Methods
• clear method: deletes all the elements
in a dictionary, leaving it empty
• Format: [Link]()
• get method: gets a value associated
with specified key from the dictionary
• Format: [Link](key, default)
• default is returned if key is not found
• Alternative to [] operator
• Cannot raise KeyError exception
51
Copyright © 2018 Pearson Education, Inc.
Some Dictionary Methods
(cont’d.)
• items method: returns all the
dictionaries keys and associated
values
• Format: [Link]()
• Returned as a dictionary view
• Each element in dictionary view is a tuple which
contains a key and its associated value
• Use a for loop to iterate over the tuples in the
sequence
• Can use a variable which receives a tuple, or can
use two variables which receive key and value
52
Copyright © 2018 Pearson Education, Inc.
Some Dictionary Methods
(cont’d.)
• keys method: returns all the
dictionaries keys as a sequence
• Format: [Link]()
• pop method: returns value associated
with specified key and removes that
key-value pair from the dictionary
• Format: [Link](key, default)
• default is returned if key is not found

53
Copyright © 2018 Pearson Education, Inc.
Some Dictionary Methods
(cont’d.)
• popitem method: returns a randomly
selected key-value pair and removes
that key-value pair from the dictionary
• Format: [Link]()
• Key-value pair returned as a tuple
• values method: returns all the
dictionaries values as a sequence
• Format: [Link]()
• Use a for loop to iterate over the values
54
Copyright © 2018 Pearson Education, Inc.
Some Dictionary Methods
(cont’d.)

55
Copyright © 2018 Pearson Education, Inc.
Dictionary Example

56
Copyright © 2018 Pearson Education, Inc.
Difference between List, Tuple,
Set, and Dictionary

57
Copyright © 2018 Pearson Education, Inc.
Difference between List, Tuple,
Set, and Dictionary (cont’d.)
List Tuple Set Dictionary
The list can be Tuple can be The set can be The dictionary can
represented by [ ] represented by ( ) represented by { be represented by
} {}
Example: [1, 2, Example: (1, 2, 3, 4, Example: {1, 2, Example: {1: “a”,
3, 4, 5] 5) 3, 4, 5} 2: “b”, 3: “c”, 4:
“d”, 5: “e”}
A list can be Tuple can be created A set A dictionary can
created using using dictionary can be created using
the list() function the tuple() function. be created using the dict() function.
the set() function
A list is mutable A tuple is A set is mutable A dictionary is
i.e we can make immutable i.e we i.e we can make mutable, but Keys
any changes in cannot make any any changes in are not duplicated.
the list. changes in the tuple. the set, but
elements are not
duplicated.
Creating an Creating an empty Creating a set Creating an empty
empty list Tuple a=set() dictionary
l=[] t=() b=set(a) d={} 58
Copyright © 2018 Pearson Education, Inc.
Summary
• This chapter covered:
– Lists, including:
• Indexing
• Techniques for processing lists
• Slicing and copying lists
• List methods and built-in functions for lists
– Tuples, including:
• Immutability
• Difference from and advantages over lists
– Plotting charts and graphs with the matplotlib Package
– Sets, including:
Creating a Set
Getting the Number of and Adding Elements
Deleting Elements From a Set
Finding the Union, Intersection, Difference, Symmetric Difference, Subsets
and Supersets of Sets
- Dictionaries

59

You might also like