Answer the following for all data structures
.append(value)
, .pop(index)
new_list = []
Other useful methods: .extend()
for value in list_name
to access values (no index needed)
for i in range(len(list_name))
to mutate individual values
for i in range(len(list_name)-1, -1, -1)
to pop items from the list
dict_name[key] = value
, .pop(key)
new_dict = {}
for key in dict_name
to access key (and access value through key)for value in dict_name.values()
to access values onlyfor key, value in dict_name.items()
to access key value pairs.add(value)
, remove(value)
new_set = set()
No index, so just one type of loop
for value in set_name
to access values(10, 20, 2)
*
to take in variable number of argumentsreturn 10, 20, 2
We can use len()
with all data structures
Write a function that takes in a filename string for a file that contains coordinates and shape names, with values separated by comma, and returns a dictionary with coordinates as key and shape name as value.
def read_file(filename):
f = open(filename, "r")
result = {} # new dictionary
for line in f:
parts = line.strip().split(",")
key = (int(parts[0]), int(parts[1]))
result[key] = parts[2]
return result
if __name__ == "__main__":
my_dict = read_file("shapes.txt")
assert my_dict == {(10, 5): 'triangle',
(5, 5): 'circle',
(6, 7): 'triangle',
(15, 10): 'square',
(20, 25): 'rectangle'}
print(my_dict)
{(10, 5): 'triangle', (5, 5): 'circle', (6, 7): 'triangle', (15, 10): 'square', (20, 25): 'rectangle'}
Write a function called split_odds_evens
that takes in a variable number of arguments and returns a tuple of lists, one list with all odd numbers, another list with all even numbers
def split_odds_evens(*values):
odds = []
evens = []
for v in values:
if v % 2 == 0:
evens.append(v)
else:
odds.append(v)
return odds, evens
if __name__ == "__main__":
result = split_odds_evens(10, 2, 1, 20, 32, 2, 4, 3, 2, 1)
assert result == ([1, 3, 1], [10, 2, 20, 32, 2, 4, 2])
print(result)
([1, 3, 1], [10, 2, 20, 32, 2, 4, 2])
Write a function called odds_evens_sets
that takes in a variable number of arguments and returns a tuple of sets, one list with all unique odd numbers, another with all unique even numbers
def odds_evens_sets(*values):
odds = set()
evens = set()
for v in values:
if v % 2 == 0:
evens.add(v)
else:
odds.add(v)
return odds, evens
if __name__ == "__main__":
result = odds_evens_sets(10, 2, 1, 20, 32, 2, 4, 3, 2, 1)
assert result == ({1, 3}, {32, 2, 4, 10, 20})
print(result)
({1, 3}, {32, 2, 4, 10, 20})
Write a python function that removes all negative numbers from an argument list. The function should mutate the argument list.