Skip to content

Instantly share code, notes, and snippets.

Last active December 29, 2021 11:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misterhtmlcss/91a1a05617a5017369a2031c060d52a5 to your computer and use it in GitHub Desktop.
Save misterhtmlcss/91a1a05617a5017369a2031c060d52a5 to your computer and use it in GitHub Desktop.
✓ Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples. Do not copy them from the textbook or any other source.
✓ Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method.
# Tuples are immutable and are therefore excellent choices for immutable data, this includes dealing with through the managing out of issues such as 'aliasing' which can cause unintended assignment bugs (Downey, A. 2015). Also Tuples should be used as the data type of choice with data that is typically permanently linked ex. phone number and name, eye colour, etc (Pythonist 2019). Another example of good data to link is geo-data and post code.
# An example could be a Tuple for the class and objects within the Tuple for the grades that change, but the size and make up of the class shouldn't; I'm ignoring drop outs in this example.
def grade_tracker():
t_CS1101_grades = ({'Roger': 76}, {'Goeun': 93}, {'Ibi': 100}, {'Suchet': None })
for student in t_CS1101_grades:
for name in student:
if student[name] == None:
student[name] = int(input(f'What grade should the {name} receive '))
return t_CS1101_grades
# Perhaps one of the most exciting things I've ever seen was learning how I could transform the above data cs1101_grades to using a tuple for the key e.g. ('Roger', 'Kondrat'). This is such an exciting capability that I've never seen until now.
# Sequence as a dictionary key. Very advantageous when doing a database look up. Also it binds the two names together. This would seem to have a few advantages, but I've been unable to confirm them as a reference, but one would be amending someone's account is less likely to be accidentally coded into a program it would seem.
def client_db():
clients = [{('Roger', 'Kondrat'): '444-333-444'}, {('Goeun', 'Gil'): '444-222-444'}, {('Ibi', 'Aseyori'): '444-444-444'}, {('Suchet', 'Jones'): '444-111-444'}]
return clients
# Return a iterable and immutable tuple for other functions to use within the program. No aliasing. Cached.
def client_search(fn):
# Load target database using a kind of dependency injection :)
target_db = fn()
# Scope of search on target database
find_first_name = input("Target first name: ")
find_last_name = input("Target last name: ")
for client in target_db:
for fname, lname in client:
# print('test', fname, lname)
if fname == find_first_name and lname == find_last_name:
contact_number = client[fname, lname]
t_return = (fname, lname, contact_number)
# Return tuple of client contact data
return t_return
return "That client isn't in our database"
# converts any sequence passed into it into a Tuple with an index included.
def lets_enumerate():
random_location_data = ["West Hills", "Central", "Crowfoot", "Harvest Hills"]
enumerated_data = []
for indexed_tup in enumerate(random_location_data):
enumerated_data += indexed_tup,
return enumerated_data
# converts two lists into an object of tuples. Other than this example, this can be useful for linked data that is permanent e.g. area code to province/state/region.
# [('Pancake Flip', 'West Hills'), ('Iceberg chase', 'Central'), ('Smoke show', 'Crowfoot'), ('Farmers Market', 'Harvest Hills')]
def lets_zip_stuff():
zipped = []
random_event_data = ["Pancake Flip", "Iceberg chase", "Smoke show", "Farmers Market"]
random_location_data = ["West Hills", "Central", "Crowfoot", "Harvest Hills"]
# Zip together each correlated sequence from each List and transform those new pairs into Tuples
for zips in zip(random_event_data, random_location_data):
zipped += {zips:'is_zipped'}
return zipped
# Take a dictionary and return a sequence of Tuples within a List
# dict_items([('Roger', 76), ('Goeun', 93), ('Ibi', 100), ('Suchet', None)])
def dict_items():
more_random_data = {'Roger': 76, 'Goeun': 93, 'Ibi': 100, 'Suchet': None }
# print('test', list(more_random_data.items()))
return more_random_data.items()
# Last line
if __name__ == "__main__":
print('\ngrade_tracker()', grade_tracker())
print('\nclient_search(client_db)', client_search(client_db))
print('\nlets_enumerate()', lets_enumerate())
print('\nlets_zip_stuff()', lets_zip_stuff())
print('\ndict_items()', dict_items())
# **************************
# Example output:
# What grade should the Suchet receive 656
# grade_tracker() ({'Roger': 76}, {'Goeun': 93}, {'Ibi': 100}, {'Suchet': 656})
# Target first name: Roger
# Target last name: Kondrat
# client_search(client_db) ('Roger', 'Kondrat', '444-333-444')
# lets_enumerate() [(0, 'West Hills'), (1, 'Central'), (2, 'Crowfoot'), (3, 'Harvest Hills')]
# lets_zip_stuff() [('Pancake Flip', 'West Hills'), ('Iceberg chase', 'Central'), ('Smoke show', 'Crowfoot'), ('Farmers Market', 'Harvest Hills')]
# dict_items() dict_items([('Roger', 76), ('Goeun', 93), ('Ibi', 100), ('Suchet', None)])
# **************************
# Reference
# "Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press."
# Hettinger, R. (2014). Are tuples more efficient than lists in Python?. Retrieved from
# Rostami, M. (2020). Why is tuple faster than list in Python?. Retrieved from
# D.K., John. (2020). Python: List vs Tuple vs Dictionary vs Set. Retrieved from
# StackOverflow. (2020). Data size in memory vs. on disk. Retrieved from
# *Nullstone Corporation. (n.d.). Constant Folding. Retrieved from
# Gunawan B, S. (2018). Python Tuple in Depth. Retrieved from
# AskPython. (n.d.). What is Python List and Tuple?. Retrieved from
# Programiz. (n.d.). Python Tuple. Retrieved from
# Pythonist. (2019). Lists vs Tuples in Python. Retrieved from
# Socratica. (2016). Python Tuples. Retrieved from
# *Note:
# Unofficial, but great resource on the topic of Constant Folding despite it's domain affiliation is:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment