What is difference between append and extend list methods in Python

What is difference between append and extend list methods in Python

Asked on December 20, 2018 in Python.
Add Comment


  • 3 Answer(s)

    The difference is,

    append: Appends object at the end.

    x = [1, 2, 3]
    x.append([4, 5])
    print (x)
    

    The  output will be [1, 2, 3, [4, 5]]

    extend: Extends list by appending elements from the iterable.

    x = [1, 2, 3]
    x.extend([4, 5])
    print (x)
    

    The output will be [1, 2, 3, 4, 5]

    Answered on December 20, 2018.
    Add Comment

    The solution is,

    append adds an element to the list, extend concatenates the first list with another list

    >>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
     
    li.append("new")
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
     
    li.append(["new", 2])
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example', ['new', 2]]
     
    li.insert(2, "new")
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
     
    li.extend(["two", "elements"])
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    
    Answered on December 20, 2018.
    Add Comment

    Let us see the solution,

        append is used to appends a single element. extend appends a list of elements.

    Remember that if you pass a list to append, it still adds one element:

    >>> a = [1, 2, 3]
    >>> a.append([4, 5, 6])
    >>> a
    [1, 2, 3, [4, 5, 6]]
    
    Answered on December 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.