LN 5 DataStructures
LN 5 DataStructures
PROGRAMMING PARADIGM
Script Programming with Python
- Data Structures
2
Object
Recall (Lecture slide 3):
Object
Dynamically typed
keeps track of types for you automatically instead of
requiring declaration code
Mutable vs Immutable
Think of an object as a box
Mutable
• An open box, not only can we see the value inside, we
can also change it. BUT we can not change its type.
Immutable
• A closed box with a clear window, we can see the value
but we can not change it.
• When value change, Python will designate a new memory
location to hold the new value
• Variable will reference that new object
Mutable vs Immutable
Mutable vs Immutable
List
Integer
String
Tuple
Mutable vs Immutable
List
A list is an ordered sequence of Python objects
• Objects can be of any type
• Objects do not have to all be the same type.
* If you need to keep track of unique values and do not care about order, use set.
9
• Create with []
Since lists are mutable objects, fruits_2 will points to the same memory
location as fruits_1. Any changes of values in fruits_2 will be reflected in
fruits_1 as well.
13
List – Operations
Example of additional list operations
17
List – Operations
Example of additional list operations
18
Tuples
• Tuples (similar to lists), are sequences of arbitrary items.
You do not need parentheses when creating tuple – it is the trailing commas that define a tuple.
However using parentheses to enclose value can be useful to help make tuple more visible.
Tuples vs Lists
We can always use tuple in place of lists, but they have
fewer functions (i.e. no append(), insert() and etc. because
they are immutable)
Dictionaries
• Dictionary (similar to lists), but
• The order of items does not matter
• Elements in dictionary can not be selected by an offset. Need to
specify unique key. The key is often a string, but can be any
immutable types (i.e. Boolean, integer, float, tuple, and etc.)
By using the same key (‘Gilliam’), we replace the original value ‘Gerry’ with ‘Terry’.
27
Set
• Set (similar to dictionaries), but with its values thrown
away leaving only the keys.
Output:
36
Output:
37
Intersection of the set with special punctuation symbol & or the set
intersection() function
39
*A superset is the opposite of a subset (all members of the second set are also members of the first).
42
For the list and tuple, the value between the square brackets is an integer
offset. For the dictionary, it’s a key. For all three, the result is a value.
43
Hands-on Activities
• Store the names of a few of your friends in a list called names. Print a message to
them. The text of each message should be the same but each message should be
personalized with the person’s name.
• Use a dictionary to store information about a person you know. Store their first name,
last name, age, and the city in which they live. You should have keys such as
first_name, last_name, age, and city. Print each piece of information stored in your
dictionary.