Python Data Structure 4 Updated
Python Data Structure 4 Updated
1
Recap of Last Class
String
Assignment /Concatenate
Slicing (e.g., Square brackets [index])
String Methods (e.g., upper(),lower(),split())
Modify Strings (e.g., replace())
Format Strings (e.g., .format())
Escape Characters (e.g., \”,\’,\n)
String Comparison/Membership (e.g., ==,!=, in, not in)
Strings are immutable
Data Structure (List)
Characteristics (e.g., indexing, changeable, …)
2
Last Labs
Be careful!
3
What is Data Structure?
Organizing, managing and storing data is important as it enables easier access and
efficient modifications. Data Structures allow you to organize your data in such a way
that enables you to store collections of data, relate them and perform operations on
them accordingly
In simple terms, data structure refers to the collection or group of data in a particular
structure. In Python, the four common data structures are: Lists, Tuples, Sets, and
Dictionaries
4
What is Data Structure?
5
Lists
Lists are used to store data of same/different data types in a sequential manner
There are addresses assigned to every element of the list, which is called as Index
To create a list, you use the square brackets and add elements into it accordingly
Index 0 1 2 3
Index -4 -3 -2 -1
6
Loop Lists (Continued)
You can loop through the list items by using a for loop
7
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list
Based on a list of names, you want a new list, containing only the names with the
letter "J" in the name
Without list comprehension you will have to write a for statement with a conditional
test inside:
8
List Comprehension
With list comprehension you can do all that with only one line of code:
The Syntax
The condition is like a filter that only accepts the items that valuate to True.
The iterable can be any iterable object, like a list, tuple, set etc.
The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before 9it
ends up like a list item in the new list
List Comprehension
10
List Comprehension
The condition if name != “James" will return True for all elements other than “James", making the
new list contain all names except “James".
We can also omit the condition if, and it will copy the original name list
11
List Comprehension
The iterable can be any iterable object, like a list, tuple, set etc.
Try the code below. What is the length of the newlist, and what is the maximum
number in the newlist?
12
List Comprehension
The expression is the current item in the iteration, but it is also the outcome, which
you can manipulate before it ends up like a list item in the new list
How can you change the above code to for loop and print the same code?
13
List Comprehension
The expression can also contain conditions, not like a filter, but as a way to
manipulate the outcome:
For example, assume we know that the name of "John" is mistakenly written as
"James", and please return "John" instead of "James" if it is "James" :
14
Sort Lists
15
Sort Lists
16
Sort Lists
17
Copy a List
How about you print List2 now (what you get from this?)
18
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference
to list1, and changes made in list1 will automatically also be made in list2
Make a copy of a list with the copy() method
19
Tuples
Tuples are similar to lists, but the only big difference is the elements inside a list can
be changed but in tuple it cannot be changed, so tuple is immutable
Tuples are written with round brackets ( while Lists with square brackets )
20
Tuples
21
Tuples
Note: When creating a tuple with only one item, remember to include a comma after the item, otherwise it
will not be identified as a tuple.
22
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a
tuple
In Python, we are also allowed to extract the values back into variables. This is called
"unpacking"
23
Unpacking a Tuple
24
Unpacking a Tuple
25
Built-in tuple function
tuple.count() function counts the number of specified element that is present in the
tuple
tuple.index() function returns the index of the specified element. If the elements are
more than one, then the index of the first element of that specified element is
returned
26
Key Difference
27
Tuple vs. List?
28
Python Sets
Python Sets
Sets are used to store multiple items in a single variable
A set is a collection which is unordered, unchangeable*, and unindexed (*set
items are unchangeable, but you can remove items and add new items)
Sets are written with curly brackets
29
Python Sets
Python Sets
Sets do not allow duplicate values, duplicate values will be ignored
30
Python Sets
Python Sets
Sets are not indexed, therefore, items cannot be accessed by indexing
31
Add Items in Sets
Python Sets
To add one item to a set, use the add() method
To add items from another set into the current set, use the update() method
32
Remove Items in Sets
Python Sets
To remove an item in a set, use the remove(), or the discard() method
33
Remove Items in Sets
Python Sets
You can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed
34
Join Sets
update() method that inserts all the items from one set into another
Note: Both union() and update() will exclude any duplicate items.
35
Keep ONLY the Duplicates in Sets
The symmetric_difference() method will return a set that contains all items from
either sets, except items that are present in both
36
What are Dictionaries?
Keys Values
The dictionary keys can be any immutable data type (i.e., numbers, strings, tuples)
Dictionary values can be just about any data type (int, lists, functions, strings, etc.)
37
Dictionary Characteristics
Dictionary is ordered
Can we use index, i.e., [], to get the item? Try this
Can we loop through it? Try this and see what you get?
38
Dictionary Characteristics
Accessing values
You can access the value of a dictionary by referring to its key name, inside square
brackets
There is also a method called get() that will give you the same result
39
Dictionary Characteristics
Get Values
The values() method will return a list of all the values in the dictionary
40
Dictionary Characteristics
Get Keys
The keys() method will return a list of all the keys in the dictionary
41
Dictionary Characteristics
Get Items
The items() method will return a list of all the items in the dictionary, as tuples in a
list
42
Dictionary Characteristics
Can you also use in to check whether a value is in dictionary or not? Try this
43
Dictionary Characteristics
Changeable
We can change, add or remove items after the dictionary has been created
You can change the value of a specific item by referring to its key name
Update Dictionary
The update() method will update the dictionary with the items from the given
argument (to update the value of an existing key)
The argument must be a dictionary, or an iterable object with key:value pairs
44
Dictionary Characteristics
45
Dictionary Characteristics
The update() method will update the dictionary with the items from a given
argument (to add new items, both key and value)
46
Dictionary Characteristics
Remove Items
The pop() method removes the item with the specified key name
47
Dictionary Characteristics
Remove Items
The del keyword removes the item with the specified key name
48
Dictionary Characteristics
Dictionary Length
49
Dictionary Characteristics
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only
be a reference to dict1, and changes made in dict1 will automatically also be made
in dict2
One way is to use the built-in dictionary method copy()
50
Dictionary Characteristics
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only
be a reference to dict1, and changes made in dict1 will automatically also be made
in dict2
Another way is to use the built-in dictionary method dict()
51
Nested Dictionaries
52
Nested Dictionaries
53
Summary of Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
54
Comparison between List and Dictionary
55
Jupyter Notebook
56