0% found this document useful (0 votes)
9 views

SSG slide 4&5 (Data Structures)

This document is a lecture on getting started with Python, covering data structures such as lists, tuples, sets, and dictionaries. It explains their properties, methods, and provides exercises for practice. The lecture also includes information on mutability, ordering, and identity operators in Python.

Uploaded by

Richard Ezemelue
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)
9 views

SSG slide 4&5 (Data Structures)

This document is a lecture on getting started with Python, covering data structures such as lists, tuples, sets, and dictionaries. It explains their properties, methods, and provides exercises for practice. The lecture also includes information on mutability, ordering, and identity operators in Python.

Uploaded by

Richard Ezemelue
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
You are on page 1/ 26

GETTING STARTED WITH PYTHON

MICHEAL OGUNDERO
EMAIL – [email protected]
LECTURE 5

MICHEAL OGUNDERO
EMAIL – [email protected]
QUESTIONS FROM LAST CLASS

1. What is the escape code for newline?


2. Print a message that includes double and single quotes using escape characters.
3. What is python keyword to prompt an input from a user?
4. Create a program that prompts the user to enter a sentence and prints it back in a title case.
DATA STRUCTURES

Data structures are containers that organize and group data types together in different ways.

Types of Data Structures:

• Lists
• Tuples
• Sets
• Dictionaries
• Compound Data Structures
LISTS

List is a datatype for mutable ordered sequence of elements.

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:

greeting = "Hello there"


greeting[0] = 'M'
This is because strings are immutable. This means to change this string; you will need to create a
completely new string.

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

The following are some useful list methods:

• len() returns how many elements are in a list.


• max() returns the greatest element of the list. How the greatest element is determined depends on
what type objects are in the list. The maximum element in a list of numbers is the largest number.
The maximum elements in a list of strings is element that would occur last if the list were sorted
alphabetically. This works because the max function is defined in terms of the greater than
comparison operator. The max function is undefined for lists that contain elements from different,
incomparable types.
• min() returns the smallest element in a list. min is the opposite of max.
• sorted() returns a copy of a list in order from smallest to largest, leaving the list unchanged.

print(sorted (list_name)) #sorts in ascending order


print(sorted(list_name, reverse = True)) #sorts in descending order
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.

name = "-".join(["García", "O'Kelly"])


print(name) #García-O'Kelly

• Append method: Append adds an element to the end of a list.

letters = ['a', 'b', 'c', 'd']


letters.append('z')
print(letters) # ['a', 'b', 'c', 'd', 'z']

Other lists methods are pop, remove, etc


EXERCISE

Create a list of your favorite colors.

1. Print the second and fourth elements from the list.


2. Print the elements from the 3rd to the 7th.
3. Print the first 3 elements.
4. Print the last 3 elements.
5. Ask the user for their favorite color and append it to the list.
6. What will be the output of the following:

names = ["Carol", "Albert", "Ben", "Donna"]


print(" & ".join(sorted(names)))
a = [1, 5, 8]
b = [2, 6, 9, 10]
c = [100, 200]

print(max([len(a), len(b), len(c)]))


print(min([len(a), len(b), len(c)]))
TUPLES

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:

location = (13.4125, 103.866667)


print("Latitude:", location[0])
print("Longitude:", location[1])
Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by
their indices. Unlike lists, however, tuples are immutable - you can't add and remove items from tuples, or
sort them in place. They also have zero indexing.
TUPLES

Tuples can also be used to assign multiple variables in a compact way.

dimensions = 52, 40, 100


length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))
The parentheses are optional when defining tuples, and programmers frequently omit them if parentheses
don't clarify the code.

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!

length, width, height = 52, 40, 100


print("The dimensions are {} x {} x {}".format(length, width, height))
EXERCISE

What would the output of the following code be?

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".

fruit = {"apple", "banana", "orange", "grapefruit"} # define a set


print("watermelon" in fruit) # false

fruit.add("watermelon”) # add an element


print(fruit) # {'grapefruit', 'orange', 'watermelon', 'banana', 'apple'} an unordered list of
elements

print(fruit.pop()) # removes a random element. Returns element to be removed e.g


grapefruit
print(fruit) # {'orange', 'watermelon', 'banana', 'apple'}
EXERCISE

What would the output of the following code be?

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.

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}


DICTIONARIES

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.

print(elements["helium"]) # prints the value mapped to "helium"

elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary


DICTIONARIES

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.

print("carbon" in elements) #True


print(elements.get("dilithium")) #None
elements.get('kryptonite', 'There\'s no such element!') # "There's no such element!"

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

Operator Meaning Example

is True if the operands are identical x is True


(refer to the same object)

is not True if the operands are not x is not True


identical (do not refer to the
same object)
EXERCISE

What would the output of the following code be?

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.

elements = {"hydrogen": {"number": 1,


"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}
}

We can access elements in this nested dictionary like this.

helium = elements["helium"] # gets the helium dictionary

hydrogen_weight = elements["hydrogen"] ["weight"] # gets hydrogen's weight


COMPOUND DATA STRUCTURES

You can also add a new key to the element dictionary.

oxygen = {"number":8,"weight":15.999,"symbol":"O"} # creates a new oxygen


dictionary
elements["oxygen"] = oxygen # assigns 'oxygen' as a key to the elements dictionary
print('elements = ', elements)
RECAP

Data Structure Ordered Mutable Constructor Example


List Yes Yes [ ] or list() [5.7, 4, 'yes', 5.7]
Tuple Yes No ( ) or tuple() (5.7, 4, 'yes', 5.7)
Set No Yes {}* or set() {5.7, 4, 'yes'}
Dictionary No No** { } or dict() {'Jun': 75, 'Jul': 89}

* 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

1. Create a list of your favorite fruits.


○ Use slicing to print the first two fruits.
○ Add two more fruits which should be provided by the user to the list.
○ Print the updated list.
○ Sort the list and print it.
2. Research two lists methods besides the ones provided and use them.
3. Research two strings methods besides the ones provided and use them.
4. Create a tuple with the temperatures of a week. Convert it to a set and print the set.
5. Create a dictionary with information about your favorite book (title, author, year). Add the genre to
the dictionary and print the updated dictionary.
6. Create a compound dictionary with information about your favorite movie (title, director, year) and
your favorite song (title, artist, year).
End of Lecture 5

You might also like