0

In the following code, by mistake, I used string concatenation on a variable defined as a list. Instead of giving an error, it split up the list elements into individual letters. What causes this? is it supposed to do this?

def strList(spam):

    #x = ''  <--- I meant say x is empty string but erroneously said a blank *list*
    x = []
    for i in range(len(spam)-1):
        x += (spam[i]+',')
    x += ('and '+spam[len(spam)-1])
    return x


spam = ['apples', 'bananas', 'tofu', 'cats', 'dogs', 'elephants']
print(strList(spam))

The answer it gave was ['a', 'p', 'p', 'l', 'e', 's', ',', 'b', 'a', 'n', 'a', 'n', 'a', 's', ',', 't', 'o', 'f', 'u', ',', 'c', 'a', 't', 's', ',', 'd', 'o', 'g', 's', ',', 'a', 'n', 'd', ' ', 'e', 'l', 'e', 'p', 'h', 'a', 'n', 't', 's'] instead of an error.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
ArNY
  • 65
  • 1
  • 9
  • 1
    It's because `+=` on a list doesn't do `append`, it does `extend`. It extends a list by adding elements from an iterable, and when you iterate a string, you get individual characters. – Tim Roberts Dec 11 '22 at 02:56

0 Answers0