0% found this document useful (0 votes)
81 views52 pages

ANL252 SU2 Jul2022

This document discusses tuples, lists, and dictionaries in Python. It defines each data type and describes how to access, modify, concatenate, and print their elements. Tuples are immutable collections of values, while lists allow modification. Dictionaries store key-value pairs and access values using keys. Common operations like indexing, slicing, concatenation, and iteration with for-loops are explained for each data type.

Uploaded by

Ebad
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)
81 views52 pages

ANL252 SU2 Jul2022

This document discusses tuples, lists, and dictionaries in Python. It defines each data type and describes how to access, modify, concatenate, and print their elements. Tuples are immutable collections of values, while lists allow modification. Dictionaries store key-value pairs and access values using keys. Common operations like indexing, slicing, concatenation, and iteration with for-loops are explained for each data type.

Uploaded by

Ebad
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/ 52

Study Unit 2

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

Fruits = (“Apple”, “Orange”, “Banana”)

• We can index this tuple using a positive index

Fruits = (“Apple”, “Orange”, “Banana”)


Index 0 Index 1 Index 2

• Alternatively, we can refer to elements of this tuple using a negative index

Fruits = (“Apple”, “Orange”, “Banana”)


Index -3 Index -2 Index -1

5/60
Example of subset
• Returning to our tuple named as ‘Fruits’

Fruits = (“Apple”, “Orange”, “Banana”)

• Creating Fruits_Subset = Fruits[0:2], obtain all elements except index 2

Fruits_Subset = (“Apple”, “Orange”)


Index 0 Index 1

• Create Fruits_Subset = Fruits[-3:-1], obtain all elements except index -1

Fruits_Subset = (“Apple”, “Orange”)


Fruits = (“Apple”, “Orange”, “Banana”)
Index -3 Index -2 Index -1
6/60
Edit and Concatenate Tuples
• Recall: Tuples are immutable.
• Values of a tuple cannot be changed.
• We are also not allowed to add a new value to an existing tuple.

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.

for counter in tuple_name:


instructions
• It is also applicable to lists and dictionaries.

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.

list_name = [element1, element2, …]


• The square brackets are not omittable.
• Contents can be any type of objects: floats, integer, Booleans, strings, tuples,
or even lists.

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

• Use multiple indexing to edit multiple items.


list_name[start index:end index] = [list with new values]

• 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

• Fruits[0:1] is a list [“Apple”]


➢ To replace a list, we need a list
➢ Fruits[0:1] = [“Papaya”]

• Fruits[0] is a string, i.e., “Apple”


➢ To replace a string, we need a string
➢ Fruits[0] = “Papaya”

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

Fruits = [“Apple”, “Orange”, “Banana”]


Vegetables = [“Spinach”, “Lettuce”, Cabbage”]

• Generate Combined = Fruits + Vegetables

Combined = [“Apple”, “Orange”, “Banana”,


“Spinach”, “Lettuce”, “Cabbage”]

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

Fruits = [“Apple”, “Orange”, “Banana”]


Vegetables = [“Spinach”, “Lettuce”, Cabbage”]

• Now merge the two lists: Combined = [Fruits, Vegetables]


1st element of Combined is Fruits

Combined = [ [“Apple”, “Orange”, “Banana”],


[“Spinach”, “Lettuce”, “Cabbage”] ]

2nd element of Combined is Vegetables


19/60
Print Lists
• Use loops to subset lists and print the items to the screen.
• Include lists in the for-statement to print the list items instead of using
range().
for counter in list_name:
instructions

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

Fruits_Price = {"Apple": 1.20, "Orange":0.70, "Banana":0.90}

• To get the price of Apple, we

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

dict_keys = ["Apple", "Orange", “Banana"]

• Using Fruits_Price.values(), we get the dictionary’s values

dict_values = ["1.20", "0.70", "0.90"]

• Using Fruits_Price.items(), we get the dictionary’s keys and values

dict_items = ([("Apple",1.20), ("Orange", 0.70),


("Banana", 0.90)])

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.

for element1, element2 in list(dictionary_name.items()):


instructions
• The for-loop can also iterate through any list created from a dictionary.
• Two temporary storage variables instead of one are in the for-loop: one for the key, one
for the value.

27/60
Example of printing dictionary items

• Printing the items of our Fruits_Price dictionary

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

• Verify that the price of Apple is 120 in Fruits_Price.

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

• Delete the key, Apple, in Fruits_Price

• Verify the key, Apple, is deleted from Fruits_Price

32/60
Add Items to Dictionary
• To add a dictionary key, we simply assign a value to a new key.

dictionary_name["new key"] = value

• 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:

def function_name(argument1, argument2, …):


instructions
return object

• 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

(This section is for your information only


because you are using Anaconda3)
Modules, Packages, Libraries
• Python packages are like directories of Python scripts, or modules.
• Modules specify functions, methods, and object types to solve certain
tasks.
• Packages may contain sub-packages or regular modules.
• Packages of standard libraries are already installed in Python.
• Library is a collection of codes to perform specific tasks without writing
our own code.

49/60
Import Packages and Modules
• In Python, we can choose to import the entire package or a specific
module of the package.

import package_name as package_alias


from package_name import module_name as module_alias

• Use an alias to refer to a specific package or module from thereon in the


program.
• Alias is advantageous if the package or module has a very long name.

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, …)

• If only a single module is imported, call it directly by its name without


referring to the package.
y = module_name(argument1, argument2, …
• If only a single module is imported with an alias, use the alias instead of
the original module name.
y = 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:

> pip install package_name


> pip3 install package_name
• “pip3” is a newer version of “pip”. Use either one for the installation.

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

• Uninstall a package by the command:


> pip uninstall package_name
> pip3 uninstall package_name

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy