0

I'm working my way through CodeAcademy and I have a question that's going unanswered there. The assignment is to take a list of lists and make a single list of all its elements. The code immediately below is my answer that worked. But what I don't understand is why "item" is treated as elements in a list for that code whereas (see comment continued below)...

m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]

def join_lists(*args):
    new_list = []
    for item in args:        
        new_list += item
    return new_list


print join_lists(m, n, o)

...the "item" in the code below is treated as the whole list instead of elements in a list. The code below gives the ouput:

 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I also tried to use: new_list.append(item[0:][0:]) thinking it would iterate through the index and sub-index but it gave the same result. I just don't understand how this is being interpreted.

m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]


def join_lists(*args):
    new_list = []
    for item in args:        
        new_list.append(item)
    return new_list


print join_lists(m, n, o)

Also, I know I could add another for-loop to the code above, and I get why that works, but I still don't understand with one line of difference why Python interprets these differently.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

8

The += in-place add operator on a list does the same thing as calling list.extend() on new_list. .extend() takes an iterable and adds each and every element to the list.

list.append() on the other hand, adds a single item to the list.

>>> lst = []
>>> lst.extend([1, 2, 3])
>>> lst
[1, 2, 3]
>>> lst.append([1, 2, 3])
>>> lst
[1, 2, 3, [1, 2, 3]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks, I think I get that. I thought it was defined in the "for item in args." But the command determines how the item gets handled. Thanks so much! – user1252778 Jun 21 '13 at 16:42
  • @user1252778: Your `args` is a list of lists; each element in it is itself a list (taken from `m`, `n` and `o` passed to the function). – Martijn Pieters Jun 21 '13 at 16:43
2

Martijn (as always) has explained this well. However, the (for reference only) Pythonic approach would be:

def join_lists(*args):
    from itertools import chain
    return list(chain.from_iterable(args))
tobias_k
  • 81,265
  • 12
  • 120
  • 179
Jon Clements
  • 138,671
  • 33
  • 247
  • 280