Monday, January 12, 2015

Python: extend() Append Elements of a List to a List

When you append a list to a list by using append() method, you'll see your list is going to be appended as a list:
>>>l=["a"]
>>>l2=["a", "b"]
>>>l.append(l2)
>>>l
['a', ['a', 'b']]
If you want to append elements of the list directly without creating nested lists, use extend() method:
>>>l=["a"]
>>>l2=["a", "b"]
>>>l.extend(l2)
>>>l
['a', 'a', 'b']

No comments: