# Noemi Cabrera
# 7 December 2021
# In this lesson, I learned how to differentiate between tuples and list, create tuples using (), access tuple elements,
# delete them with del(), slice them with [], and unpack them by assigning each item to a variable. Also, I learned to
# convert lists into tuples using tuple() and tuples into lists using list(). Laslty, I performed basic tuple operations
# and functions similar to how you do with lists. For example, concatenation, identifying if tuples are equal and identical, etc.
# The key concept is that tuples cannot be changed.
# I didn't have any major difficulties in this lesson.
# In this code, a tuple with integer values only is created. The type of the T_int variable is displayed.
# Tuples have () instead of [].
# Create a homogeneous int tuple
T_int = (10, -4, 59, 58, 23, 50)
type(T_int)
# In this code, a tuple with string values only is created. The type of the T_int variable is displayed.
# Tuples have () instead of [].
# Create a homogeneous string tuple
T_string = ("word", "letter", "vowel", "spell", "book", "write", "read")
type(T_string)
# In this code, a tuple with multiple data type values is created. The type of the T_int variable is displayed.
# In this code, the tuple contains a string, an integer, a float, and a list.
# Create heterogeneous tuples
T = ("Tobias", 23, 25.3, [])
type(T)
# In this code, a tuple with multiple data type values is created. The type of the T_int variable is displayed.
# In this code, the tuple contains a tuple, a string, and a variable containing the current time.
# The type of "T" is displayed.
# Create heterogeneous tuples
# A datetime object can be a tuple element
from datetime import datetime
now = datetime.today()
T = ((1.5,2.6), "home", now)
type(T)
# In this code, a tuple with a single element is created. Tuples need to have more than one element, so Python
# recognizes this code as a string. The type of "T" is displayed.
T = ("switch") # This is not a tuple
type(T)
# In this code, a tuple with a single element is created. Tuples need to have more than one element, so a
# comma needs to be added. The type of "T" is displayed.
T = ("switch",) # Note the comma after the string makes T a tuple
type(T)
# In this code, the names_list list is sorted alphabetically ans stored in the sorted_list variable. Then, it's converted into a tuple by
# using tuple() and stored into the 'names_tuple' variable. The type of 'names_tuple' is displayed.
# List of employee names
names_list = ["Suresh", "Colette", "Skye", "Hiroto", "Tobias", "Tamara", "Jin", "Joana", "Alton"]
# Sort the names alphabetically
sorted_list = sorted(names_list)
# Convert list into tuple
names_tuple = tuple(sorted_list)
# List converted into a tuple
print(type(names_tuple))
# Print the first and last name in the tuple
print("First name is: {:s}".format(names_tuple[0]))
print("Last name is: {:s}".format(names_tuple[-1]))
# In this code, a for in loop is created. The user is asked to enter an integer 3 times and these are squared and
# saved in the "L" list. This list is then converted into a tuple and saved as "T". The tuple is displayed.
# Lastly, using anothe for..in loop, each of the elements in the tuple is displayed ina new line.
# Collect 3 int numbers from a user
L = []
for i in range(3):
tmp = int(input("Enter an int {:d}/3: ".format(i)))
L.append(tmp ** 2)
# Convert the list into a tuple
T = tuple(L)
# Print the content of the tuple
print("Tuple of squares is:", T)
# Print each of the tuple elements on a new line
for i in range(3):
print("T[{0:d}] = {1:d}".format(i, T[i]))
# In this code, a tuple with multiple data type elements is created and saved as "T". Then, the last item from
# the tuple is appended the integer 44. The tuple is displayed.
# Since the tuple wasn't being changed, an error is not displayed.
T = ("Tobias", 23, 25.3, [])
# A list inside a tuple can change
T[-1].append(44)
# The tuple did NOT change, it still refers to the same list; only the list was changed
print(T)
# In this code, a tuple containing different variables is created and saved as tuple1.
# Each variable has a different data type value. The tuple is displayed.
# [ ] Create a tuple that consists of the following variables
x = 5
l = [4.4, 5.3]
s = "something"
t = (9, 0)
tuple1 = (x,l,s,t)
print(tuple1)
# In this code, the third item in the "T" tuple is changed using slicing. Since this item is a list,
# we first indicate the index of the item in the list we want to change and then re-assign it a value.
# The tuple with the modified list is displayed
# [ ] Change the third element of T to [59, 20.4]
T = ([43.6, 34], [49, 59], [50, 34.6], [39, 49])
# TODO: your code here
T[2][0] = 59
T[2][1] = 20.4
print(T)
# In this code, the contents of the variables T1 and T2 are combined. First, these tuples are converted into
# lists, added together, and saved in T. Then, the list "T" is converted into a tuple. The combined
# tuple "T" is displayed.
# [ ] Write a program to merge the content of T1 and T2 into one tuple T
# Correct output should be T = (5, 4, 3, 9, 2, 12)
# T = ((5, 4, 3), (9, 2, 12)) is an incorrect output
# Hint: Use list to/from tuple conversion
T1 = (5, 4, 3)
T2 = (9, 2, 12)
T = list(T1) + list(T2)
T = tuple(T)
print("T =",T)
# In this code, the tuple "T" is sliced so that the numerical and the string values are in different tuples.
# Square brackets are used too make the slices and each one is assigned to a new variable.
# The tuples are displayed.
T = (12, 24, 'name', 'city')
# Slice the tuple into numerical and textual tuples
numerical_tuple = T[0:2]
print(numerical_tuple)
textual_tuple = T[-2:]
print(textual_tuple)
# In this code, the order of the variables in the (e1, e2) tuple is changed. e1 is assigned e2, and e2 is
# assigned e1. The before and after swapping tuples are displayed.
# Swap variables using tuple unpacking
e1 = 5
e2 = 109
print("\nBefore swapping:")
print("e1 = {:3d}\t e2 = {:3d}".format(e1, e2))
e1, e2 = e2, e1
print("\nAfter swapping:")
print("e1 = {:3d}\t e2 = {:3d}".format(e1, e2))
# In this code, the split_name function is defined. This function converts the argument entered into a list
# and then the first and second item are put into different variables. The function returns a tuple with the
# first and last name.
# The user is then asked to enter his or her full name. This is passed as the function's argument.
# The 'first_name' tuple from the function is asigned to 'first' and 'last_name' is assigned to 'last'.
# The first and last name are displayed.
# Split a full name into the first and last names
def split_name(name):
names = name.split(" ")
first_name = names[0]
last_name = names[-1]
# pack the variables into a tuple, then return the tuple
return (first_name, last_name)
# Ask user for input
name = input("Enter your full name: ")
# Unpack the returned tuples into first, last variables
# looks like the function returns 2 variables
first, last = split_name(name)
# Unpacked variables can be used separately
print("First name: {:s}".format(first))
print("Last name: {:s}".format(last))
# In this code, the contents of the "T" tuple are split into two different tuples by using slicing.
# "T1" starts at index 0 and ends at index 2. "T2" starts at index 3 and ends at the last item in the tuple.
# The tuples are displayed.
# [ ] Write a program to split the content of T into T1 and T2
# T1 = (5, 4, 3)
# T2 = (9, 2, 12)
T = (5, 4, 3, 9, 2, 12)
T1 = T[:3]
print("T1 =", T1)
T2 = T[3:]
print("T2 =", T2)
# In this code, the "T" tuple is unpacked into 4 different variable. Each item in the tuple is assigned
# to a new variable by using slicing. The variables contents are displayed.
# [ ] Write an expression to unpack `T` into:
# 1) x = 5
# 2) l = [3, 5.3]
# 3) s = 'something
# 4) t = (9, 0)
T = (5, [3, 5.3], 'something', (9, 0))
#TODO: Your code goes here
x = T[0]
l = T[1]
s = T[2]
t = T[3]
print("After unpacking the tuple:", T)
print("x =", x)
print("l =", l)
print("s =", s)
print("t =", t)
# In this code, the date function is imported from the datetime module and used to get the current date. Then the churrent_date()
# function is defined. This function returns the current date in the form of a tuple.
# Lastly, the tuple the function returns is unpacked and each item is assigned to a different variable. Today's date is
# displayed using phython style formatting.
# [ ] Complete the function `current_date` to return today's month, day, and year
# Hint: Use an appropriate function from the datetime module
from datetime import date
c_date = date.today()
def current_date():
#TODO return month, day, year
year = c_date.timetuple()[0]
month = c_date.timetuple()[1]
day = c_date.timetuple()[2]
return (month, day, year)
m, d, y = current_date()
print("Today's date is: {:2d}/{:2d}/{:4d}".format(m,d,y))
# In this code, the in and not in operators are used to check if the tuple "T" contains certain items.
# 4 is in "T", so True displays. 5 is not in "T", so True displays. False is not in "T", so false displays.
T = (4, [5, 6], 'name', 3.5, True)
print("4 contained in T?", 4 in T)
print("5 not contained in T?", 5 not in T )
print("False contained in T?", False in T)
# In this code, the is and == operators are used to check if tuples "T1" and "T2" are equal and identical.
# Since both tuples have the same data, they are equal. However, they are not identical because they are not saved in the same
# memory location.
# Equivalent tuples, not identical
T1 = (10, [2, 4], 59)
T2 = (10, [2, 4], 59)
if (T1 == T2):
print("Equal tuples")
else:
print("Not equal tuples")
if (T1 is T2):
print("Identical tuples")
else:
print("Not identical tuples")
# In this code, the is and == operators are used to check if tuples "T1" and "T2" are equal and identical.
# Since both tuples have the same data, they are equal. They are also identical because they refer to the same object and same location, not to two
# different locations. If one is modified , the other one is too.
# Identical tuples (also equivalent)
T1 = (10, [2, 4], 59)
T2 = T1
if (T1 == T2):
print("Equal tuples")
else:
print("Not equal tuples")
if (T1 is T2):
print("Identical tuples")
else:
print("Not identical tuples")
# "T1" and "T2" are equal and identical. because they have the same data and are saved in the same memory location.
# The first item within the list in tuple "T1" is modified, so the "T2" tuple is also modified.
# The contents of the variables are displayed.
# Changing one of 2 identical tuples
T1 = (10, [2, 4], 59)
T2 = T1
# A change in T1 is a change in T2
T1[1][0] = 20
print("T1 = ", T1)
print("T2 = ", T2)
# In this code, the tuples "T1" and "T2" are concatenated / added together. The result is saved in the "T" variable and
# displayed.
T1 = ("First", "Last")
T2 = ("Middle",) # single element tuple
# Concatenate two tuples
T = T1 + T2
print(T)
# In this code, one slice from the tuple "T1" is added to one slice from the tuple "T2". The result is saved in "T" and
# then displayed.
T1 = (10, [2, 4], 59)
T2 = (59, [2, 4], 'name', 3.5, True)
# Concatenate sliced tuples
T = T1[1:] + T2[0:2]
print(T)
# In this code, the length of the "T1" tuple is get and displayed by using the len() function in a print statement.
# The list is counted as one item.
# length of tuple
T1 = (10, [2, 4], 59)
print(len(T1))
# In this code, a for..in loop is used to iterate over the range that equals the length of "T1" and print each of the items
# of "T1" according to their index count.
# Iterate over elements of a tuple
T1 = (10, [2,4], 59)
for i in range(len(T1)):
print("T1[{:d}] = {}".format(i, T1[i]))
# In this code, tuples "T1" and "T2" are concatenated/ added together and saven in the "T" avriable. The contents of "T"
# are displayed.
# [ ] Write a program to merge the content of T1 and T2 into one tuple T
# Correct output should be T = (5, 4, 3, 9, 2, 12),
# T = ((5, 4, 3), (9, 2, 12)) is an incorrect output
# You should NOT use lists in your solution but concatenation
T1 = (5, 4, 3)
T2 = (9, 2, 12)
T = T1 + T2
print("T =", T)
# In this code, the user is asked to enter a whole number. Then, the 'in' operator in an if/else statement is used to check
# if the number entered is in the tuple "T". If the number is in "T", an statement saying so is displayed.
# If the number is not in "T", a statement saying so is displayed..
# [ ] Write a program to prompt the user for a number, then test if the number is contained in T
T = (23, 45, 93, 59, 35, 58, 19, 3)
num = input("Enter a whole number: ")
if num in T:
print(num,"is contained in 'T'")
else:
print(num,"is not contained in 'T'")
# In this code, the largest_num() function is defined. This function returns the largest number found in the tuple "T".
# To achieve this, I used a for...in loop to iterate through each item in "T" and then a while loop within this loop
# to compare each item and see which one is the largest. Once found, the largest number is assigned is to "l_num".
# Write a function to return the largest element in a tuple T
T = (23, 45, 93, 59, 35, 58, 19, 3)
def largest_num():
l_num = T[0]
for num in T:
while num > l_num:
l_num = num
return l_num
largest_num()
# In this code, a for..in loop is used to iterate through each item in the tuple "T" and then each item is added to get the total sum of
# the numbers. Lastly, the average of the tuple is calculated by dividing the sum by the length of the tuple. The average is displayed.
# [ ] Write a program to compute the average of the elements in T
T = (23, 45, 93, 59, 35, 58, 19, 3)
total_items = len(T)
sum_items = 0
for num in T:
sum_items = sum_items + num
average = sum_items/total_items
print("Average of the tuple 'T': ",average)