Differences between append and extend list methods in python

    append( )
    • takes one argument: an iterator or an object
    • adds its argument as a single element to the end of the list, so the length of the list will always increase by one after execution
    • append() with a dictionary as an argument will add the entire dictionary to the end of the list
    • The list will become nested because of append method if another list is appended.
    • append has constant time complexity, O(1)
    extend( )
    • takes one argument and it should be an iterator
    • iterates over its argument adding each element to the end of the list, so length of list increases by the number of elements in the argument.
    • extend() with a dictionary as an argument will add the keys (not values) to the end of the list iteratively
    • The list will not be nested because of extend method
    • time complexity of extend is O(k)
    Both append and extend methods take one argument, modify the list in-place and returns None, but there are few differences between the methods:
    The append method takes one argument and it can be an iterator or a python object and adds that as a single element to the end of the list, so the length of the list will always increase by one after execution
    The extend method takes one argument and it should be an iterator and iterates over the argument adding each element to the end of the list, so length of list increases by the number of elements in the argument.
    append() with a dictionary as an argument will add the entire dictionary to the end of the list
    extend() with a dictionary as an argument will add the keys (not values) of dictionary to the end of the list iteratively
    append() with a string as an argument will add the entire string to the end of the list
    extend() with a string as an argument will add each character of the string as an element to the end of the list iteratively
    The list will become nested because of append method if another list is appended.
    The list will not be nested because of extend method
    append has constant time complexity, O(1)
    time complexity of extend is O(k)


difference-between-append-and-extend-list-methods-in-python
gk