Difference between append and extend list methods in Python









  • What is the difference between extend and append methods in Python

    append() takes one argument and it can be an iterator or other data types (int, float, bool etc)
    extend() takes one argument and it has to be an iterator (int, float, bool etc. are not allowed)





  • Differences between append and extend list methods

    append() 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 the append
    extend() iterates over its argument adding each element to the end of the list, so length of list increases by number of elements in the argument.



  • Differences between append and extend methods

    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 of dictionary to the end of the list iteratively (values are not added)


  • Differences between append and extend methods

    Both + and += operators are defined for list. They are semantically similar to extend. list1 + list2 creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list. list1 += list2 modifies the list in-place, so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable. list1 = list1 + list2 is not equivalent to += (list1 = list1 + list2 creates a brand new list and assigns it to list1 while list1 += list2 modifies the list in-place, so no new object is created)




datai analytics