Search code examples
pythonmutable

List non-mutating method


Is there in python any method that instead of mutate the original list it returns a new object?

In JavaScript there is at least one:

const originalArray = [1,2,3]
originalArray.concat(4) // returns a new array

Solution

  • In Python, this will return a new list:

    originalArray = [1,2,3]
    originalArray + [4]
    

    Or if you want to create a new copy of the list use slices:

    originalArray[:]
    

    List comprehensions will also create a new list:

    [x for x in originalArray]
    

    This is yet another way:

    import copy
    copy.copy(originalArray)
    

    And there's also the built-in copy() method, as shown in Ronald's answer.