3

I loop through a list of lists and when I append the item to an array it adds each letter separately and not the word as a whole unless I remove the '[]'.. why is it occurs, just curious? Example:

Just curious to know why this behavior occurs

def printTable(lists):
    for list in lists:
        s = []
        for item in list:
            s += item
            print(s)
        print()     


tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

printTable(tableData)

instead of adding each item to the list, it adds each letter (while removing the list data type it adds them by letters as excepted) just curious why is that happens.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
Din
  • 33
  • 3

2 Answers2

5

instead of s += item try this:

s.append(item)

when you said s += item it is equivalent to s = s + item, and surely s is list and item is a string, and in python strings are iterable, so that's why it will look like this.

look at the example below:

a = 'hi'
print(list(a))
['h', 'i']

and also as @roganjosh said in comments:

Note that using list as a variable name is not good, list is built-in in python.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
1

Welcome to Stackoverflow. This is quite an interesting question.

Your outer loop sets list (poor choice of name, by the way, as that's also the name of a Python built-in type) to each sublist in turn, and the inner one sets item to the value of each word in the inner list.

Had you written

s = s + item

instead of

s += item

then you would have seen an exception raised because of the expression on the right-hand side:

>>> [] + "abc"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

TypeError: can only concatenate list (not "str") to list

The behaviour of the += operator isn't quite the same however. There is an interesting discussion in this question. The bottom line is that if the right-hand operator to the += is iterable then the interpreter iterates over it, appending each item to the list.

If you are simply looking to add each item to the s list, you should instead use the append method:

s.append(item)
holdenweb
  • 33,305
  • 7
  • 57
  • 77