SSG slide 4&5 (Data Structures)
SSG slide 4&5 (Data Structures)
MICHEAL OGUNDERO
EMAIL – [email protected]
LECTURE 5
MICHEAL OGUNDERO
EMAIL – [email protected]
QUESTIONS FROM LAST CLASS
Data structures are containers that organize and group data types together in different ways.
• Lists
• Tuples
• Sets
• Dictionaries
• Compound Data Structures
LISTS
A list is defined using square brackets and always holds other data which are separated by commas. This
data could be a mix of any of the former datatypes. Lists are ordered and each individual element has
their index beginning from 0 (or -1 from the end).
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December']
print(months[0]) # January
print(months[1]) # February
print(months[7]) # August
print(months[-1]) # December
print(months[-2]) # November
print(months[25]) # IndexError: list index out of range
SLICE AND DICE WITH LISTS
We can pull more than one value from a list at a time by using slicing. When using slicing, it is important to
remember that the lower index is inclusive and the upper index is exclusive.
q3 = months[6:9]
print(q3) # [ 'July', 'August', 'September']
first_half = months[:6]
print(first_half) # ['January', 'February', 'March', 'April', 'May', 'June']
second_half = months[6:]
print(second_half) # ['July', 'August', 'September', 'October', 'November', 'December']
Notice this is still different than just indexing a single element, because you get a list back with this
indexing. The colon tells us to go from the starting value on the left of the colon up to, but not including,
the element on the right. This type of indexing works exactly the same on strings, where the returned
value will be a string.
MUTABILITY AND ORDER
Mutability is about whether or not we can change an object once it has been created. If an object can be
changed (like a list can), then it is called mutable. However, if an object cannot be changed without
creating a completely new object (like strings), then the object is considered immutable.
my_lst = [1, 2, 3, 4, 5]
my_lst[0] = 'one'
print(my_lst) # ['one', 2, 3, 4, 5]
As shown above, you are able to replace 1 with 'one' in the above list. This is because lists are mutable.
However, the following does not work:
Order is about whether the position of an element in the object can be used to access the element. Both
strings and lists are ordered. We can use the order to access parts of a list and string.
LISTS METHODS
• Join method: The join() method takes all items in an iterable and joins them into one string. A string
must be specified as the separator.
It's a data type for immutable ordered sequences of elements. They are often used to store related pieces
of information. Consider this example involving latitude and longitude:
In the second line, three variables are assigned from the content of the tuple dimensions. This is called
tuple unpacking. We can use tuple unpacking to assign the information from a tuple into multiple
variables without having to access them one by one and make multiple assignment statements.
If we won't need to use dimensions directly, we could shorten those two lines of code into a single line
that assigns three variables in one go!
tuple_a = 1, 2
tuple_b = (1, 2)
print(tuple_a == tuple_b)
print(tuple_a[1])
SETS
A set is a data type for mutable unordered collections of unique elements. One application of a set is to
quickly remove duplicates from a list. Sets can be created from lists or created using curly {} braces.
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums) # {1, 2, 3, 6}
SETS
Sets support the in operator the same as lists do.You can add elements to sets using the ‘add’ method,
and remove elements using the ‘pop’ method, similar to lists. Although, when you pop an element from a
set, a random element is removed because sets, unlike lists, are unordered so there is no "last element".
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
b = set(a)
print(len(a) - len(b))
DICTIONARIES
A dictionary is a datatype for mutable objects that store mappings of unique keys to values. It is a mutable
unordered data structure that stores mappings of unique keys to values. Here's a dictionary that stores
elements and their atomic numbers.
Dictionaries can have keys of any immutable type, like integers or tuples, not just strings. Dictionary keys
must be immutable, that is, they must be of a type that is not modifiable e.g lists cannot be used as keys,
strings and tuples can be keys. In Python, any immutable object (such as an integer, boolean, string, tuple) is
hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash
value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.
This is why Python requires us to use immutable data types for the keys in a dictionary. It's not even
necessary for every key to have the same type. On the other hand, values can be lists and then can be
indexed into each list with 0 based indexing. We can look up values or insert new values in the dictionary
using square brackets that enclose the key.
We can check whether a value is in a dictionary the same way we check whether a value is in a list or set
with the ‘in’ keyword. Dicts have a related method that's also useful, ‘get’. get looks up values in a
dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't
found.
Carbon is in the dictionary, so True is printed. Dilithium isn’t in our dictionary so None is returned by get
and then printed. If you expect lookups to sometimes fail, ‘get’ might be a better tool than normal square
bracket lookups because errors can crash your program.
IDENTITY OPERATORS
In Python, is and is not are used to check if two values are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.
n = elements.get("dilithium")
print(n is None) #True
print(n is not None) #False
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(a == b)
print(a is b)
print(a == c)
print(a is c)
COMPOUND DATA STRUCTURES
We can include containers in other containers to create compound data structures. For example, the
dictionary below maps keys to values that are also dictionaries.
* You can use curly braces to define a set like this: {1, 2, 3}. However, if you leave the curly braces empty
like this: {} Python will instead create an empty dictionary. So to create an empty set, use set().
** A dictionary itself is mutable, but each of its individual keys must be immutable.
ASSIGNMENTS