It counts how many unique names there are in the file
It returns an integer with the count
Use a list for this
Name file names.py and submit your attendance - part two.
assert count_names("names.txt") ==11
Write a function – solution
def count_names(file_name): f =open(file_name, "r") name_list = []for line in f: name = line.strip()if name notin name_list and name !="": name_list.append(name) f.close()returnlen(name_list)def main():assert count_names("names.txt") ==11main()
It counts how many unique names there are in the file
It returns an integer with the count
Use a dictionary for this
assert count_names("names.txt") ==11
Write a function – solution
def count_names(file_name): f =open(file_name, "r") name_dict = {}for line in f: name = line.strip()if name notin name_dict and name !="": name_dict[name] ="" f.close()returnlen(name_dict)def main():assert count_names("names.txt") ==11main()
Submit attendance - part three
Go to Python Tutor, visualize the execution, and submit your attendance.
Remove values using for x in list:
my_list = [2, 3, 1, 2]for value in my_list: my_list.remove(value)
Append values using for x in list:
my_list = [2, 3, 1, 2]for value in my_list: my_list.append(value +1)
Cannot change size while iterating
It’s not possible to remove or add items to a list/dictionary inside a for x in data_structure loop:
Weird behavior:
my_list = [2, 3, 1, 2]for value in my_list: my_list.remove(value)my_list
[3, 2]
Infinite loop:
my_list = [2, 3, 1, 2]for value in my_list: my_list.append(value +1) # this causes an infinite loop
Cannot change size while iterating
It’s not possible to remove or add items to a list/dictionary inside a for x in data_structure loop:
Error:
my_dict = {2: 0, 3: 1, 1: 0}for key in my_dict: my_dict.pop(key) # this causes an error