Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Shwetha Shyam sunder
1,369 PointsFor those who solved the morse code challenge, can you please explain why we have to use append instead of +=?
When I used pattern1 += 'dot' vs. pattern1.append('dot'), the results were entirely different
class Letter:
def __init__(self, pattern=None):
self.pattern = pattern
def __str__(self):
pattern1 = []
for letter in self.pattern:
if letter == ".":
pattern1.append('dot') <<-------- why do we use append here instead of += ?
elif letter == "_":
pattern1.append('dash')
'-'.join(pattern1)
return '-'.join(pattern1)
1 Answer
markmneimneh
14,133 PointsBecause pattern1 = [] .... it is an array
You append to an array.
and you concatenate strings.
if I have an array of strings .... Example:
friends = ['Mark', 'Jimmy', 'Albert']
friends.append('Lucus')
print(friends)
# now try to use plus as you are thinking
friends += 'Lucy'
print(friends)
look what happens:
['Mark', 'Jimmy', 'Albert', 'Lucus'] # first print
['Mark', 'Jimmy', 'Albert', 'Lucus', 'L', 'u', 'c', 'y'] #2nd print
Lucy was treated as an array of characters that were added to the friend's arry.
Shwetha Shyam sunder
1,369 PointsShwetha Shyam sunder
1,369 PointsThank you so much!!!