An introductory course to the Python 3 programming language, with a curriculum aligned to the Certified Associate in Python Programming (PCAP) examination syllabus (PCAP-31-02).
https://knowledgebase.hyperlearning.ai/courses/introduction-to-python
In this module we will introduce additional common collection data structures available in Python and associated methods, including:
# Create an empty tuple
empty_tuple = ()
print(empty_tuple)
# Create a tuple with only 1 element by using a trailing comma
tuple_one_element_1 = 'elem1',
print(tuple_one_element_1)
tuple_one_element_2 = 10,
print(tuple_one_element_2)
tuple_one_element_3 = ('a', )
print(tuple_one_element_3)
# If we forget the trailing comma, then Python will recognise it as a string
print(type(tuple_one_element_1))
tuple_one_element_4 = ('a')
print(type(tuple_one_element_4))
# Create a tuple with 5 elements
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
# Initialise a tuple with a list
my_tuple_from_a_list = tuple(["a", "b", "c"])
my_tuple_from_a_list
# Create a heterogeneous tuple containing information about an individual
individual_tuple = ("Barack", "Obama", 59)
print(individual_tuple)
# Access elements in a tuple by their index numbers
my_tuple = ("Barack", "Obama", "04/08/1961", 59, "Male", 1.85, "American")
print(my_tuple[0])
print(my_tuple[3])
print(my_tuple[-1])
print(my_tuple[-2])
# Use slice notation on tuples
print(my_tuple[:])
print(my_tuple[2:])
print(my_tuple[:4])
print(my_tuple[2:5])
print(my_tuple[1::2])
# Using the len() function on tuples
print(len(my_tuple))
# Test whether an element exists in a tuple
if 'Obama' in my_tuple:
print(f"This tuple correponds to information about Barack Obama")
else:
print(f"This tuple does not correspond to information about Barack Obama")
# Delete a tuple
print(my_tuple_from_a_list)
del my_tuple_from_a_list
print(my_tuple_from_a_list)
# Join two tuples to create a new tuple
my_first_tuple = ('a', 1, 'b', 2, 'c', 3)
my_second_tuple = ('d', 4, 'e', 5, 'f', 6)
my_third_tuple = my_first_tuple + my_second_tuple
print(my_third_tuple)
# Use tuple packing to pack values into a single tuple
barack_obama = "Barack", "Obama", 59
print(barack_obama)
print(type(barack_obama))
# Use sequence unpacking to assign values to variables from a given sequence
barack_obama_first_name, barack_obama_last_name, barack_obama_age = barack_obama
print(barack_obama_first_name)
print(barack_obama_last_name)
print(barack_obama_age)
# Swap values assigned to two different variables
a = 10
b = 99
print(a)
print(b)
(a, b) = (b, a)
print(a)
print(b)
# Create a tuple
my_tuple = (0, 1, 0, 1, 1, 0, 0, 1, 1, 1)
# tuple.count(x)
print(my_tuple.count(0))
print(my_tuple.count(1))
print(my_tuple.count(2))
# tuple.index(x)
print(my_tuple.index(0))
print(my_tuple.index(1))
print(my_tuple.index(2))
# Create a tuple
my_diatomic_tuple = (0, 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
# Iterate the tuple using a while loop
i = 0
while i < len(my_diatomic_tuple):
print(f'Diatomic Sequence - Element #{i + 1}: {my_diatomic_tuple[i]}')
i += 1
# Iterate the tuple using a for loop with the range function
for x in range(len(my_diatomic_tuple)):
print(f'Diatomic Sequence - Element #{x + 1}: {my_diatomic_tuple[x]}')
# Iterate the tuple using a for loop with the in operator
for elem in my_diatomic_tuple:
print(elem)
# Iterate the tuple using a for loop with the in operator and enumerate function
for idx, elem in enumerate(my_diatomic_tuple):
print(f'Diatomic Sequence - Element #{idx + 1}: {elem}')
import math
# Return both the circumference and area of a circle given a radius
def circle(radius):
""" Return the (circumference, area) of a circle given its radius """
circumference = 2 * math.pi * radius
area = math.pi * radius * radius
return (circumference, area)
my_radius = 10
my_cirumference, my_area = circle(my_radius)
print(f'The circumference of a circle of radius {my_radius}cm is {my_cirumference}cm')
print(f'The area of a circle of radius {my_radius}cm is {my_area}cm\u00b2')
# Create a list of tuples
my_list_of_tuples = [(1, 'abc'), (2, 'def'), (3, 'ghi')]
print(my_list_of_tuples)
print(my_list_of_tuples[0])
print(my_list_of_tuples[0][0])
print(my_list_of_tuples[1])
print(my_list_of_tuples[1][1])
print(my_list_of_tuples[2])
print(my_list_of_tuples[2][0])
print(type(my_list_of_tuples))
# Create a tuple of lists
my_tuple_of_lists = ([1, 2, 3], ['abc', 'def', 'ghi'])
print(my_tuple_of_lists)
print(my_tuple_of_lists[0])
print(my_tuple_of_lists[0][0])
print(my_tuple_of_lists[1])
print(my_tuple_of_lists[1][1])
print(type(my_tuple_of_lists))
# Create an immutable 3 x 3 identity matrix
identity_matrix = ((1, 0, 0), (0, 1, 0), (0, 0, 1))
for row in identity_matrix:
for elem in row:
print(elem, end=' ')
print()
# Create an empty dictionary
my_empty_dict = {}
print(my_empty_dict)
# Create a dictionary mapping countries (keys) to their population size in millions (value)
country_population_dict = {
"China": 1394,
"India": 1326,
"Japan": 126,
"United Kingdom": 66,
"United States": 330
}
print(country_population_dict)
# Create a dictionary using the dict() function and a list of tuples
country_population_dict = dict([
("China", 1394),
("India", 1326),
("Japan", 126),
("United Kingdom", 66),
("United States", 330)
])
print(country_population_dict)
# Access a dictionary value item by its key using square brackets
japan_population_m = country_population_dict["Japan"]
print(f'The population of Japan is {japan_population_m}m')
# Access a dictionary value item by its key using the get() method
print(f'The population of China is {country_population_dict.get("China")}m')
# Perform a lookup using a non-existent key using square brackets
brazil_population_m = country_population_dict["Brazil"]
print(f'The population of Brazil is {brazil_population_m}m')
# Perform a lookup using a non-existent key using the get() method
print(f'The population of Brazil is {country_population_dict.get("Brazil")}m')
# Create a dictionary of GDP rankings by country
gdp_rankings_dict = {
"China": 2,
"India": 8,
"Japan": 3,
"United Kingdom": 5,
"United States": 1
}
print(gdp_rankings_dict)
# Modify the ranking of an existing country
gdp_rankings_dict["India"] = 7
print(gdp_rankings_dict)
# Add a country to the population dictionary
print(country_population_dict)
country_population_dict["South Korea"] = 52
print(country_population_dict)
# Remove a key:value pair from the country population dictionary usign the del keyword
print(country_population_dict)
del country_population_dict["Japan"]
print(country_population_dict)
# Remove a key:value pair from the country population dictionary usign the pop() method
country_population_dict.pop("United Kingdom")
print(country_population_dict)
# Remove the last inserted key:value pair using the popitem() method
country_population_dict.popitem()
print(country_population_dict)
# Delete the GDP rankings dictionary
print(gdp_rankings_dict)
del gdp_rankings_dict
print(gdp_rankings_dict)
# Use a for loop to iterate through the keys in a given dictionary, printing the keys
for key in country_population_dict:
print(key)
print()
# Use a for loop to iterate through the keys in a given dictionary, printing the values
for key in country_population_dict:
print(country_population_dict[key])
# Use the values() method to iterate over the values of a dictionary
for v in country_population_dict.values():
print(v)
print()
# Use the items() method to iterate over both keys and values of a dictionary
for k, v in country_population_dict.items():
print(f'The population of {k} is {v}m')
# Test for the existence of a key in a given dictionary
if "South Korea" in country_population_dict:
print(f'The population of South Korea is {country_population_dict["South Korea"]}m')
else:
print('South Korea does not exist in our dictionary of populations.')
# Create a dictionary of keys (1 - 10) and values (key squared) using dictionary comprehension
squares_dict = {num: num*num for num in range(1, 11)}
print(squares_dict)
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
"Mercury": 91_691_000,
"Venus": 41_400_000,
"Mars": 78_340_000,
"Jupiter": 628_730_000,
"Saturn": 1_275_000_000,
"Uranus": 2_723_950_000,
"Neptune": 4_351_400_000
}
print(f'Distance between the Earth and the other planets in the Solar System (km):\n{earth_planets_distance_km_dict}\n')
# Convert to AU using dictionary comprehension
km_to_au = 149_600_000
earth_planets_distance_au_dict = { planet: round((km / km_to_au), 2) for (planet, km) in earth_planets_distance_km_dict.items() }
print(f'Distance between the Earth and the other planets in the Solar System (AU):\n{earth_planets_distance_au_dict}')
# Create a dictionary of planets within 100km of the Earth
planetary_neighbour_limit_km = 100_000_000
earth_closest_planets_dict = { k:v for (k, v) in earth_planets_distance_km_dict.items() if v < planetary_neighbour_limit_km }
print(f'Distance between the Earth and our closest planets in the Solar System (km):\n{earth_closest_planets_dict}')
# Create a dictionary of average planetary distances from the Earth, using km for the inner planets and AU for the outer planets
km_to_au = 149_600_000
inner_planet_limit_km = 100_000_000
earth_planets_km_au_dict = { k: ( v if v < inner_planet_limit_km else round((v / km_to_au), 2) ) for (k, v) in earth_planets_distance_km_dict.items() }
print(f'Distance between the Earth and the other planets in the Solar System (km for inner planets and AU for outer planets):\n{earth_planets_km_au_dict}')
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
"Mercury": 91_691_000,
"Venus": 41_400_000,
"Mars": 78_340_000,
"Jupiter": 628_730_000,
"Saturn": 1_275_000_000,
"Uranus": 2_723_950_000,
"Neptune": 4_351_400_000
}
# Filter to keep only the inner planets
inner_planets = ["Mercury", "Venus", "Earth", "Mars"]
earth_inner_planets_distance_km_dict = { key: earth_planets_distance_km_dict[key] for key in set(inner_planets).intersection(earth_planets_distance_km_dict.keys()) }
print(earth_inner_planets_distance_km_dict)
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
"Mercury": 91_691_000,
"Venus": 41_400_000,
"Mars": 78_340_000,
"Jupiter": 628_730_000,
"Saturn": 1_275_000_000,
"Uranus": 2_723_950_000,
"Neptune": 4_351_400_000
}
print(earth_planets_distance_km_dict)
# Create a shallow copy of this dictionary
shallow_copy_dict = earth_planets_distance_km_dict
shallow_copy_dict["Earth"] = 0
# Modify the original dictionary and observe changes to the shallow copy
earth_planets_distance_km_dict["Neptune"] = 29.09
print(earth_planets_distance_km_dict)
print(shallow_copy_dict)
import copy
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
"Mercury": 91_691_000,
"Venus": 41_400_000,
"Mars": 78_340_000,
"Jupiter": 628_730_000,
"Saturn": 1_275_000_000,
"Uranus": 2_723_950_000,
"Neptune": 4_351_400_000
}
print(earth_planets_distance_km_dict)
# Create a deep copy of this dictionary
deep_copy_dict = copy.deepcopy(earth_planets_distance_km_dict)
deep_copy_dict["Earth"] = 0
# Modify the original dictionary and observe no changes to the deep copy
earth_planets_distance_km_dict["Neptune"] = 29.09
print(earth_planets_distance_km_dict)
print(deep_copy_dict)
import pprint
# Create a nested dictionary
nested_multiplication_table_2d_dict = {
1: {
1:1, 2:2, 3:3, 4:4, 5:5
},
2: {
1:2, 2:4, 3:6, 4:8, 5:10
},
3: {
1:3, 2:6, 3:9, 4:12, 5:15
},
4: {
1:4, 2:8, 3:12, 4:16, 5:20
},
5: {
1:5, 2:10, 3:15, 4:20, 5:25
}
}
pprint.pprint(nested_multiplication_table_2d_dict)
# Create the same nested dictionary using dictionary comprehension
nested_multiplication_table_2d_dict = { key1: {key2: key1 * key2 for key2 in range(1, 6)} for key1 in range(1, 6) }
pprint.pprint(nested_multiplication_table_2d_dict)
# Create a list of tuples containing countries and their size in km^2
country_area_tuples = [("Russia", 17_098_242), ("Canada", 9_984_670), ("United States", 9_857_348), ("China", 9_596_961)]
print(country_area_tuples)
# Convert this list of tuples to an equivalent dictionary
country_area_dict = { key[0]: key[1] for key in country_area_tuples}
pprint.pprint(country_area_dict)
# Create a sparse matrix with a dictionary of tuple keys
sparse_matrix_dict = {(0, 1): 1, (2, 2): 2, (4, 1): 3}
print(f'The value of the element at row 0 and column 1 is {sparse_matrix_dict.get((0, 1), 0)}')
print(f'The value of the element at row 0 and column 3 is {sparse_matrix_dict.get((0, 3), 0)}')
print(f'The value of the element at row 2 and column 1 is {sparse_matrix_dict.get((2, 1), 0)}')
print(f'The value of the element at row 2 and column 2 is {sparse_matrix_dict.get((2, 2), 0)}')
print(f'The value of the element at row 4 and column 1 is {sparse_matrix_dict.get((4, 1), 0)}')
import pprint
# Create a dictionary
earth_planets_distance_km_dict = {
"Mercury": 91_691_000,
"Venus": 41_400_000,
"Mars": 78_340_000,
"Jupiter": 628_730_000,
"Saturn": 1_275_000_000,
"Uranus": 2_723_950_000,
"Neptune": 4_351_400_000
}
pprint.pprint(earth_planets_distance_km_dict)
print()
# dict.clear()
nested_multiplication_table_2d_dict = { key1: {key2: key1 * key2 for key2 in range(1, 6)} for key1 in range(1, 6) }
pprint.pprint(nested_multiplication_table_2d_dict)
nested_multiplication_table_2d_dict.clear()
pprint.pprint(nested_multiplication_table_2d_dict)
print()
# dict.copy()
copy_dict = earth_planets_distance_km_dict.copy()
pprint.pprint(copy_dict)
print()
# dict.fromkeys(keys, value)
keys = [2, 3, 5, 7, 11]
prime_dict = dict.fromkeys(keys)
pprint.pprint(prime_dict)
v = "prime"
labelled_prime_dict = dict.fromkeys(keys, v)
pprint.pprint(labelled_prime_dict)
print()
# dict.get(key, default)
print(earth_planets_distance_km_dict.get("Venus"))
print(earth_planets_distance_km_dict.get("Earth"))
print(earth_planets_distance_km_dict.get("Earth", 0))
print()
# dict.items()
print(earth_planets_distance_km_dict.items())
print()
# dict.keys()
print(earth_planets_distance_km_dict.keys())
print()
# dict.pop(key, default)
print(earth_planets_distance_km_dict.pop("Neptune"))
print(earth_planets_distance_km_dict.pop("Earth", 0))
print()
# dict.popitem()
earth_planets_distance_km_dict["Earth"] = 0
print(earth_planets_distance_km_dict)
earth_planets_distance_km_dict.popitem()
print(earth_planets_distance_km_dict)
print()
# dict.setdefault(key, value)
pluto_average_distance_km = earth_planets_distance_km_dict.setdefault("Pluto", 4_970_600_000)
print(pluto_average_distance_km)
print(earth_planets_distance_km_dict)
print()
# dict.update(iterable)
dict_updates = {"Sun": 151_460_000, "Asteroid Belt": 390_400_000}
earth_planets_distance_km_dict.update(dict_updates)
pprint.pprint(earth_planets_distance_km_dict)
print()
# dict.values()
print(earth_planets_distance_km_dict.values())
# len()
pprint.pprint(earth_planets_distance_km_dict)
print(len(earth_planets_distance_km_dict))