Why is appending to a list create a sub-list?

I wanted to append the last two items of “lst” on to the end of lst. My code does this but puts the last to items in a sub-list. Why is it doing this?

#Write your function here
def append_sum(lst):
  lst.append(lst[-2:])
  return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))

This outputs

[1, 1, 2, [1, 2]]

You want extend not append. append will add one item to the list (in your case that is another list), extend will add multiple items to the list (in your case it would add 1 and 2 as two individual items).

1 Like

To elaborate a little on @jagking’s answer…

.append() will add whatever is passed to it into the list. In your case, lst[-2:] evaluates to a list and so it’s a list object which is added to the end of the list with append().

You can either iterate yourself over those items to add them:

def append_sum(lst):
    for item in lst[-2:]:
        lst.append(item)
    return lst

print(append_sum([1, 1, 2])) # output -> [1, 1, 2, 1, 2]

Alternatively, you can save yourself the work and use extend.

def append_sum(lst):
    lst.extend(lst[-2:])
    return lst

print(append_sum([1, 1, 2])) # output -> [1, 1, 2, 1, 2]

:slight_smile:

Extend worked.

#Write your function here
def append_sum(lst):
  lst.extend(lst[-2:])
  return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))

produced

[1, 1, 2, 1, 2]

Thank you for explaining why this was was happening. I understand the difference now.

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.