I'm trying to understand why, computationally, using += to add to a list, where square brackets have not been used to encapsulate the value, results in a single character at a time being added to the list as an element.
I hope that the question is clear; here is an example:
In:
def generate_sentences(subjects, predicates, objects):
lst1 = []
lst2 = []
lst3 = []
lst4 = []
lst5 = []
subjects = sorted(subjects)
predicates = sorted(predicates)
objects = sorted(objects)
for i in subjects:
for j in predicates:
for k in objects:
lst1 += i + " "
lst2 += (i + " ")
lst3 += [i + " "]
lst4.append(i + " ")
lst5.append([i + " "])
print("+= no paren: ")
print(lst1)
print(" ")
print("+= paren: ")
print(lst2)
print(" ")
print("+= brackets: ")
print(lst3)
print(" ")
print("append standard: ")
print(lst4)
print(" ")
print("append with brackets: ")
print(lst5)
generate_sentences(["John", "Mary"], ["hates", "loves"],\
["apples", "bananas"])
generate_sentences(["Vlad", "Hubie"], ["drives"],\
["car", "motorcycle", "bus"])
and
Out:
+= no paren:
['H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ']
+= paren:
['H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ']
+= brackets:
['Hubie ', 'Hubie ', 'Hubie ', 'Vlad ', 'Vlad ', 'Vlad ']
append standard:
['Hubie ', 'Hubie ', 'Hubie ', 'Vlad ', 'Vlad ', 'Vlad ']
append with brackets:
[['Hubie '], ['Hubie '], ['Hubie '], ['Vlad '], ['Vlad '], ['Vlad ']]