Python Syntax Practice Solutions

## Task: Use a for loop to create a list of values 0, 2, 4, …, 18
nums = []

# TODO
for x in range(0,20,2):
    nums.append(x)

# list comprehension equivalent
nums = [x for x in range(0,20,2)]

# print the whole list
print(nums)

# print without list notations
for x in nums:
    print(x, end=" ")
print()

## Task: Create a new list with all non-alpha chars removed
chars = [chr(x) for x in range(50, 100)]
alpha = []

# TODO
# list comprehension with conditional statement
# note: we could store store back into chars since RHS is ceated BEFORE LHS assignment
alpha = [c for c in chars if c.isalpha()]

# buggy, elements are removed
# for elem in chars:
#     if not elem.isalpha():
#         chars.remove(elem)

# fix, work backwards through our indices to avoid skipping an element after deletion
for index in range(len(chars) - 1,-1,-1):
    if not chars[index].isalpha():
        chars.remove(chars[index])

print(alpha)
print(chars)


## Task: Create a new dictionary from dct that only includes those in house Gryffindor
dct = { "Potter"    : "Gryffindor",
        "Granger"   : "Gryffindor",
        "Malfoy"    : "Slytherin",
    	"Diggory"   : "Hufflepuff"}
gryff = {}

# TODO
# for loop
for key in dct:                         # Potter
    # conditional
    if dct[key] == "Gryffindor":        # dct["Potter"] == "Gryffindor"
        # append to dictionary
        gryff[key] = dct[key]           # gryff["Potter"] = dct["Potter"] = "Gryffindor"

# dictionary comprehension equivalent
dct = {key:dct[key] for key in dct if dct[key] == "Gryffindor"}

print(gryff)
print(dct)


## Task: Create a new list from the hogwarts list of dictionaries
##       that only includes those in house Gryffindor
hogwarts = [    {"name" : "Potter",     "house" : "Gryffindor"},
                {"name" : "Granger",    "house" : "Gryffindor"},
                {"name" : "Malfoy",     "house" : "Slytherin"},
                {"name" : "Diggory",    "house" : "Hufflepuff"}]

# TODO
# two valid comprehensions for this excercise
liGryff = [{"name":person["name"], "house":person["house"]} for person in hogwarts if person["house"]=="Gryffindor" ]
liGryff = [student for student in hogwarts if student["house"]=="Gryffindor"]

# verbose equivalent
newGryff = []
for student in hogwarts:
    if student["house"]=="Gryffindor":
        newGryff.append(student)

print(liGryff)
print(newGryff)