Instruction: The get_name_list() function returns a list of all the names in the parameter: name_list, with a given letter provided in parameter: to_look_for.
Question: If I remove the square brackets of 'name' in 'a_list += [name]' expression, it will show the following wrong output. However, if the square brackets or 'append()' method is used, the right output will be produced (2nd correct output below). I wonder why without the square brackets in [name], the right output is not produced?
Wrong output:
names with d ['J', 'a', 'd', 'e']
names with k ['M', 'i', 'k', 'e', 'y']
Wrong code:
def main():
names = ["Jasper", "Jade", "Mikey", "Giani"]
names_d = get_name_list(names, "d")
names_k = get_name_list(names, "k")
print("names with d", names_d)
print("names with k", names_k)
def get_name_list(name_list, to_look_for):
a_list = []
for name in name_list:
#print(name)
if to_look_for in name:
print(name)
a_list += name
#a_list.append(name)
return a_list
main()
Correct output:
names with d ['Jade']
names with k ['Mikey']
Correct code:
def main():
names = ["Jasper", "Jade", "Mikey", "Giani"]
names_d = get_name_list(names, "d")
names_k = get_name_list(names, "k")
print("names with d", names_d)
print("names with k", names_k)
def get_name_list(name_list, to_look_for):
a_list = []
for name in name_list:
#print(name)
if to_look_for in name:
print(name)
#a_list += name
a_list.append(name)
return a_list
main()