Posts

Showing posts with the label Python(Lists)

What is the difference between list method extend() and operators + or += in Python

Image
  In Python, list support + and += operators. They could do the same thing as the method extend(). extend(): iterate through the iterable object and append each element from the iterable to the end of the list to be extended. Its parameter could be any iterable. >>> a = ['a','b','c'] >>> b = ['x','y','z'] >>> a.extend(b) >>> a ['a', 'b', 'c', 'x', 'y', 'z'] + operator: instead of extending the list in place, it creates a new list leaving original list untouched; it is not as effcient as two others.  >>> a = ['a','b','c'] >>> b = ['x','y','z'] >>> c = a + b >>> c ['a', 'b', 'c', 'x', 'y', 'z'] += operator: it extends the list in place which is the same as the extend() method. >>> a = ['a','b','c

The difference of list methods between append() and extend() in Python

Image
  Python lists are mutable, you can add objects to the list in place. Both append() and extend() methods could do the trick. append(): add a single object to the end of the list >>> l = ['a', 'b', 'c'] >>> l.append(['d','e','f']) >>> l ['a', 'b', 'c', ['d', 'e', 'f']] extend(): add all the elements from the iterable to the end of the list >>> l.extend(['d','e','f']) >>> l ['a', 'b', 'c', 'd', 'e', 'f']