ANL252 SU2 Jul2022
ANL252 SU2 Jul2022
Data Types
and Functions
Tuples
Define Tuples
• A collection of values written as comma-separated items between a pair of
round brackets.
tuple_name = (element1, element2, …)
• Tuples are not specifically designed for mathematical operations.
• A tuple is like a database record
• Example: Employee_A1 = (“Jimmy Chow”, “Engineer”, “Grade 2”)
• The items in a tuple can be numeric, string, or a mixture of both.
• Useful when sharing data with others but not giving others the permission to
edit the contents (aka, Immutable --- the contents cannot be changed)
3/60
Subset and Index Tuples
• Use index operator [] to access specific elements in a tuple.
• The index begins with 0 and ends with the number of elements minus 1.
• To subset multiple elements, put the start and end indices, connected by a
colon in the index operator.
tuple_subset = tuple_name[start:end]
• Important: The end index is NOT included in the subsetting procedure.
• Apply negative indices to access elements starting from the last element.
4/60
Example of index
• Suppose we have a tuple of fruits, named as Fruits
5/60
Example of subset
• Returning to our tuple named as ‘Fruits’
7/60
Length of Tuples
• The length of a tuple is the number of elements in it.
• Use as an index to subset a tuple
• Control the indexing so that the indices do not get out of range.
tuple_length = len(tuple_name)
8/60
For-Loops and Tuples
• Tuple elements are can accessible by running a for-loop iteratively.
• Put the name of the tuple in the for-statement directly.
9/60
Lists
Create Lists
• A Python list is just like a tuple with two main differences:
➢Data are comma-separated and wrapped by a pair of square brackets.
➢Content is modifiable.
• We can construct a Python list in a similar fashion like a tuple.
11/60
Subset Lists
• Use index operator [] to access specific elements in a list.
• All indexing and subsetting techniques for tuples are applicable to lists.
list_subset = list_name[start:end]
12/60
Modify Lists
• Modify specific list items by subsetting and assigning new values to them.
list_name[index] = new value
• The list of new values will occupy the locations within [start index:end index]
loactions on the left-hand side. The list on the left-hand side will expand or
shrink accordingly.
13/60
Examples of modifying lists
Index 0 Index 1 Index 2
Replacement
Replace &
expand
14/60
Some subtle points
15/60
Concatenate Lists
• We can concatenate multiple lists into one by “adding” them together.
combined_list = list1 + list2 + …
• Addition operation “+” is used to concatenate objects such as string, tuples,
or lists.
• Concatenating lists is recommended if content and type of the lists are
identical.
• Even if the nature of the two lists is not identical, it is sometimes quite
convenient to store the data in one list for later use.
16/60
Example of concatenating lists
• Suppose we have two lists, Fruits and Vegetables
17/60
Merge Lists
• Meaning and source of the elements in a concatenated list with different nature
of data will become untraceable with time.
• Merge two lists into a new list without combining the elements together.
• Each element of the new list is a list and not a single value.
• Define a new list by putting the list names as elements.
List_name = [list1, list2, …]
• Use index to refer to a whole sub-list.
• Possible to trace back the origin and meaning of the data in the new list.
18/60
Example of merging lists
• Suppose we have two lists, Fruits and Vegetables
20/60
Enter Data to Lists
• User-defined instead of pre-defined values for list items.
• Let users enter their own data by the input() function.
• Store the input into a list.
• Do not limit the number of entries and use a while-loop with appropriate
exit condition.
21/60
Dictionaries
Define and Access Dictionaries
• A dictionary is an unordered set of key:value pairs.
• The keys must be unique within one dictionary.
• The key:value pairs are separated by commas and wrapped in a pair of
braces.
dictionary_name = {"key1":value1, "key2":value2, …}
• Dictionaries are indexed by keys, which are usually strings or numbers.
• Extract values in a dictionary by the keys.
value = dictionary_name["key"]
23/60
Examples of Dictionaries
• Let us create a dictionary for the prices of our Fruits list
Apple_Price = Fruits_Price["Apple"]
24/60
Print Dictionaries
• Printing syntax for dictionaries is quite different from tuples and lists.
• It is possible to use the key to extract a value, but index operator [] cannot
refer to the keys.
• Use .keys() and .values() to extract the dictionary’s keys and values.
• Apply .item() to extract all keys and values in the same step.
dictionary_name.keys()
dictionary_name.values()
dictionary_name.items()
25/60
Examples of printing dictionaries
• Using Fruits_Price.keys(), we get the dictionary’s keys
26/60
Print Dictionaries Items
• A dict_items() object contains tuples with keys and values as items.
• Use a for-loop and the index operator to print the contents.
• Extend the for-loop so that indices are omitted when referring to dictionary items.
27/60
Example of printing dictionary items
28/60
Edit Dictionaries
• Change a value of a dictionary by assigning a new value to a certain key.
• The value can be a numeric value, a character string, a tuple, or a list.
dictionary_name["key"] = value
29/60
Example of editing dictionary
• Let us change the price of Apple from 1.20 to 120.
Fruits_Price["Apple"] = 120
30/60
Change Dictionary Keys
• Editing a key in a dictionary is not straightforward.
• The keys are immutable and cannot be changed directly.
• Instead, we can create a new key in a dictionary, take over the values from
the old key, and then delete the old key.
• The syntax del deletes an object in Python, including a dictionary key.
del object
• Once an object is deleted, it will no longer be available in the program.
31/60
Example of deleting
32/60
Add Items to Dictionary
• To add a dictionary key, we simply assign a value to a new key.
• The syntax is just the same as the syntax to edit an existing key.
• The only difference is that the key in the index operator must be a new one
here, and an existing one for editing.
33/60
Merge Dictionaries
• To merge two dictionaries, Python offers two options.
• Syntax for Python version 3.9 onwards uses the “Bitwise Or” operator “|” to
merge two dictionaries:
new_dictionary = dictionary1 | dictionary2
• Syntax for Python version 3.5 onwards:
new_dictionary = {**dictionary1, **dictionary2}
34/60
Integrated Methods and
Functions
Functions
• Functions are routine programs for value processing.
• Values are passed on to functions as arguments/parameters and results will
be returned as output to the user.
• E.g., int() removes all decimal digits of a value and returns an integer as
result.
36/60
Built-In Functions
• Built-in functions are integrated in Python, e.g., print(), input().
• Here is a list of all Python built-in functions in alphabetical order.
abs() all() any() ascii() bin()
bool() breakpoint() bytearray() bytes() callable()
chr() classmethod() compile() complex() delattr()
dict() dir() divmod() enumerate() eval()
exec() filter() float() format() frozenset()
getattr() globals() hasattr() hash() help()
hex() id() input() int() isinstance()
issubclass() iter() len() list() locals()
map() max() memoryview() min() next()
object() oct() open() ord() pow()
print() property() range() repr() reversed()
round() set() setattr() slice() sorted()
staticmethod() str() sum() super() tuple()
type() vars() zip() __import__()
• (Source: https://docs.python.org/3/library/functions.html)
37/60
Built-In Methods in Python
• Methods are routines that are applied to the objects they are attached to.
• E.g., .format() for formatting string, .keys(), .values() and
.items() for dictionaries.
• Methods return results to the program once they are applied on defined
objects during runtime.
• Each method is only applicable to certain object types.
• The list of some common methods can be found on:
https://www.w3schools.com/python/python_ref_tuple.asp
https://www.w3schools.com/python/python_ref_list.asp
https://www.w3schools.com/python/python_ref_dictionary.asp
https://www.w3schools.com/python/python_ref_string.asp
38/60
Discussion
• What are the components of a built-in function or method, and where can
we get those information before applying them in our program?
• Can we avoid the use of functions or methods and write such routines by
ourselves?
39/60
User-Defined Functions
• User-defined functions are functions that we write to suit our own needs.
• They will only be executed when they are called from the main program.
• A function consists of four parts:
1. Function name
2. Arguments
3. Instructions
4. Output object (or value)
41/60
Correct Use of User-Defined Functions
• No “outsourcing” of main program parts to functions because of “program
cleanliness”.
• Debugging is challenging if the code jumps between main program and
functions.
• Rules of thumb for using user-defined functions:
1. Same routine appears more than once in main program.
2. Combination of various functions is used on multiple occasions.
3. Increase of main program’s efficiency.
42/60
Syntax of User-Defined Functions
• The def-syntax indicates the definition of a function:
• Functions are called in the main program by integrating the function name
with the arguments at an appropriate place.
… (Main program)
y = function_name(argument1 = object1,
argument2 = object2, …)
print(y)
… (Continue with main program)
43/60
Example: user-defined functions
44/60
Activity
Boston housing data:
Use Jupyter lab.
Go to the ANL252_HousingData notebook file and run through the cells that
apply a user function to summarise values found in array, tuples and lists for the
housing dataset
There are also graphical plots you can apply to help you explore the data
Discuss your observations from the program outputs
45/60
Discussion
• When is it appropriate for us to write a user-defined function?
46/60
Modules, Packages and
Libraries
49/60
Import Packages and Modules
• In Python, we can choose to import the entire package or a specific
module of the package.
50/60
Call Modules
• If the whole package is imported, refer the package or its alias as prefix
and call the module after a dot (.).
y = package_name.module_name(argument1, argument2, …)
y = package_alias.module_alias(argument1, argument2, …)
51/60
Install Packages with pip/pip3
• More Python packages are available on the internet.
• Download and install them by the pip or pip3 Python package.
• Use PowerShell or Command Prompt as well (or similar terminal apps
from other operation systems) to execute the following command:
52/60
Upgrade and Uninstall Packages
• To update/upgrade a package, we need to type the following syntax in the
terminal apps.
> pip install package_name --upgrade
> pip3 install package_name --upgrade
53/60
Common Packages in Python
• Here are some common packages for data analytics in Python.
Package Description
matplotlib Creates data visualisation
NumPy Manages multi-dimensional arrays
pandas Handles two-dimensional data tables
pendulum Provides complex coding for dates and times
requests Sends HTTP requests from Python code
scikit-learn Provides tools of data analytics
scipy Carries out scientific and technical computations
sqlite3 Manages SQL database in Python
54/60