Questions tagged [immutability]
Immutability is the inability to modify data after it has been created. Modifications are instead made by copying the data. A property of immutable data is that it is *referentially transparent*.
                                	
	immutability
    
                            
                        
                    
            3,703
            questions
        
        
            715
            votes
        
        
            27
            answers
        
        
            1.8m
            views
        
    Remove specific characters from a string in Python
                I'm trying to remove specific characters from a string using Python. This is the code I'm using right now. Unfortunately, it appears to do nothing to the string.
for char in line:
    if char in "...
            
        
       
    
            663
            votes
        
        
            13
            answers
        
        
            193k
            views
        
    Why are exclamation marks used in Ruby methods?
                In Ruby some methods have a question mark (?) that ask a question like include? that ask if the object in question is included, this then returns a true/false.
But why do some methods have ...
            
        
       
    
            555
            votes
        
        
            16
            answers
        
        
            107k
            views
        
    Why are mutable structs “evil”?
                Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this question).
What's the actual problem with mutability and ...
            
        
       
    
            422
            votes
        
        
            17
            answers
        
        
            192k
            views
        
    What is meant by immutable?
                What exactly does immutable mean - that is, what are the consequences of an object being mutable or immutable? In particular, why are Java's Strings immutable?
My understanding is that the ...
            
        
       
    
            417
            votes
        
        
            16
            answers
        
        
            59k
            views
        
    Is a Java string really immutable?
                We all know that String is immutable in Java, but check the following code:
String s1 = "Hello World";  
String s2 = "Hello World";  
String s3 = s1.substring(6);  
System.out.println(s1); // Hello ...
            
        
       
    
            389
            votes
        
        
            18
            answers
        
        
            241k
            views
        
    Const in JavaScript: when to use it and is it necessary?
                I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):
const x = ...
            
        
       
    
            295
            votes
        
        
            13
            answers
        
        
            146k
            views
        
    What is the difference between shallow copy, deepcopy and normal assignment operation?
                import copy
a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}
a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)
print("immutable - id(a)==id(a1)", id(a) ==...
            
        
       
    
            290
            votes
        
        
            16
            answers
        
        
            669k
            views
        
    Correct way to push into state array
                I seem to be having issues pushing data into a state array.
I am trying to achieve it this way:
this.setState({ myArray: this.state.myArray.push('new value') })
But I believe this is incorrect way ...
            
        
       
    
            276
            votes
        
        
            14
            answers
        
        
            71k
            views
        
    Why is immutability so important (or needed) in JavaScript?
                I am currently working on React JS and React Native frameworks. On the half way road I came across Immutability or the Immutable-JS library, when I was reading about Facebook's Flux and Redux ...
            
        
       
    
            255
            votes
        
        
            27
            answers
        
        
            140k
            views
        
    How to make an immutable object in Python?
                Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override __setattr__, because then you can't even set attributes ...
            
        
       
    
            238
            votes
        
        
            26
            answers
        
        
            107k
            views
        
    Immutability of Strings in Java
                Consider the following example.
String str = new String();
str  = "Hello";
System.out.println(str);  //Prints Hello
str = "Help!";
System.out.println(str);  //Prints Help!
Now, ...
            
        
       
    
            233
            votes
        
        
            76
            answers
        
        
            17k
            views
        
    What's the best name for a non-mutating "add" method on an immutable collection? [closed]
                Sorry for the waffly title - if I could come up with a concise title, I wouldn't have to ask the question.
Suppose I have an immutable list type. It has an operation Foo(x) which returns a new ...
            
        
       
    
            229
            votes
        
        
            19
            answers
        
        
            315k
            views
        
    String is immutable. What exactly is the meaning? [duplicate]
                I wrote the following code on immutable Strings.
public class ImmutableStrings {
    public static void main(String[] args) {
        testmethod();
    }
    private static void testmethod() {
     ...
            
        
       
    
            229
            votes
        
        
            14
            answers
        
        
            146k
            views
        
    What would a "frozen dict" be?
                A frozen set is a frozenset.  
A frozen list could be a tuple.  
What would a frozen dict be? An immutable, hashable dict.  
I guess it could be something like collections.namedtuple, but that is ...
            
        
       
    
            221
            votes
        
        
            19
            answers
        
        
            192k
            views
        
    Enums in Javascript with ES6
                I'm rebuilding an old Java project in Javascript, and realized that there's no good way to do enums in JS.
The best I can come up with is: 
const Colors = {
    RED: Symbol("red"),
    BLUE: Symbol("...
            
        
       
    
            215
            votes
        
        
            11
            answers
        
        
            96k
            views
        
    Immutable vs Unmodifiable collection [duplicate]
                From the Collections Framework Overview:  
  Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not ...
            
        
       
    
            213
            votes
        
        
            8
            answers
        
        
            44k
            views
        
    Why can tuples contain mutable items?
                If a tuple is immutable then why can it contain mutable items?
It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being ...
            
        
       
    
            209
            votes
        
        
            20
            answers
        
        
            288k
            views
        
    Immutable vs Mutable types
                I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:
class RoundFloat(float):
    def __new__(cls, val):
        ...
            
        
       
    
            202
            votes
        
        
            13
            answers
        
        
            115k
            views
        
    Why .NET String is immutable? [duplicate]
                As we all know, String is immutable. What are the reasons for String being immutable and the introduction of StringBuilder class as mutable?
            
        
       
    
            202
            votes
        
        
            12
            answers
        
        
            106k
            views
        
    Mutable vs immutable objects
                I'm trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I'm having trouble understanding ...
            
        
       
    
            198
            votes
        
        
            17
            answers
        
        
            122k
            views
        
    Remove a property in an object immutably
                I am using Redux. In my reducer I'm trying to remove a property from an object like this:
const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}
And I want to have ...
            
        
       
    
            189
            votes
        
        
            8
            answers
        
        
            130k
            views
        
    Error: "Cannot modify the return value" c#
                I'm using auto-implemented properties. 
I guess the fastest way to fix following is to declare my own backing variable?
public Point Origin { get; set; }
Origin.X = 10; // fails with CS1612
  Error ...
            
        
       
    
            176
            votes
        
        
            7
            answers
        
        
            82k
            views
        
    Swift make method parameter mutable?
                How can I deal with this error without creating additional variable? 
func reduceToZero(x:Int) -> Int {
    while (x != 0) {
        x = x-1            // ERROR: cannot assign to 'let' value 'x'
  ...
            
        
       
    
            176
            votes
        
        
            15
            answers
        
        
            133k
            views
        
    Immutable array in Java
                Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn't actually prevent one from doing something like
final int[] array = new int[] {0, 1, 2, 3};
...
            
        
       
    
            174
            votes
        
        
            13
            answers
        
        
            41k
            views
        
    How to avoid "too many parameters" problem in API design?
                I have this API function:
public ResultEnum DoSomeAction(string a, string b, DateTime c, OtherEnum d, 
     string e, string f, out Guid code)
I don't like it. Because parameter order becomes ...
            
        
       
    
            156
            votes
        
        
            10
            answers
        
        
            68k
            views
        
    Advantages of stateless programming?
                I've recently been learning about functional programming (specifically Haskell, but I've gone through tutorials on Lisp and Erlang as well). While I found the concepts very enlightening, I still don't ...
            
        
       
    
            145
            votes
        
        
            7
            answers
        
        
            27k
            views
        
    What is the difference between immutable and const variables in Rust?
                I learned that if a variable is not explicitly declared mutable using mut, it becomes immutable (it cannot be changed after declaration). Then why do we have the const keyword in Rust? Aren't they the ...
            
        
       
    
            140
            votes
        
        
            10
            answers
        
        
            120k
            views
        
    Remove value from object without mutation
                What's a good and short way to remove a value from an object at a specific key without mutating the original object?
I'd like to do something like:
let o = {firstname: 'Jane', lastname: 'Doe'};
let ...
            
        
       
    
            140
            votes
        
        
            12
            answers
        
        
            34k
            views
        
    Why does C# disallow readonly local variables? [closed]
                Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?
            
        
       
    
            137
            votes
        
        
            22
            answers
        
        
            162k
            views
        
    Aren't Python strings immutable? Then why does a + " " + b work?
                My understanding was that Python strings are immutable.
I tried the following code:
a = "Dog"
b = "eats"
c = "treats"
print a, b, c
# Dog eats treats
print a + " " + b + " " + c
# Dog eats treats
...
            
        
       
    
            136
            votes
        
        
            3
            answers
        
        
            55k
            views
        
    How do I work around mutability in moment.js?
                I've run into a problem where I have to store the initial values of a moment object but I'm having some trouble preventing my variable from changing along with the original object.
Unfortunately ...
            
        
       
    
            132
            votes
        
        
            9
            answers
        
        
            111k
            views
        
    Does Python have an immutable list?
                Does python have immutable lists?
Suppose I wish to have the functionality of an ordered collection of elements, but which I want to guarantee will not change, how can this be implemented? Lists are ...
            
        
       
    
            129
            votes
        
        
            7
            answers
        
        
            210k
            views
        
    Java Immutable Collections
                From Java 1.6 Collection Framework documentation:
Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable. [...] Collections that ...
            
        
       
    
            127
            votes
        
        
            8
            answers
        
        
            63k
            views
        
    How do I create an immutable Class?
                I am working on creating an immutable class.
I have marked all the properties as read-only. 
I have a list of items in the class.
Although if the property is read-only the list can be modified. 
...
            
        
       
    
            119
            votes
        
        
            10
            answers
        
        
            163k
            views
        
    Replace Multiple String Elements in C#
                Is there a better way of doing this... 
MyString.Trim().Replace("&", "and").Replace(",", "").Replace("  ", " ")
         .Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower();
I've ...
            
        
       
    
            114
            votes
        
        
            12
            answers
        
        
            84k
            views
        
    Is Integer Immutable
                I know this is probably very stupid, but a lot of places claim that the Integer class in Java is immutable, yet the following code:
Integer a=3;
Integer b=3;
a+=b;
System.out.println(a);
Executes ...
            
        
       
    
            111
            votes
        
        
            10
            answers
        
        
            41k
            views
        
    What does immutable mean?
                If a string is immutable, does that mean that....
(let's assume JavaScript)
var str = 'foo';
alert(str.substr(1)); // oo
alert(str); // foo
Does it mean, when calling methods on a string, it will ...
            
        
       
    
            111
            votes
        
        
            5
            answers
        
        
            17k
            views
        
    val-mutable versus var-immutable in Scala
                Are there any guidelines in Scala on when to use val with a mutable collection versus using var with an immutable collection? Or should you really aim for val with an immutable collection?
The fact ...
            
        
       
    
            102
            votes
        
        
            4
            answers
        
        
            7k
            views
        
    If Python strings are immutable, why does it keep the same id if I use += to append to it?
                Strings in Python are immutable, which means the value cannot be changed. However, when appending to the string in the following example, it looks like the original string memory is modified since the ...
            
        
       
    
            100
            votes
        
        
            9
            answers
        
        
            36k
            views
        
    Hashable, immutable [duplicate]
                From a recent SO question (see Create a dictionary in python which is indexed by lists) I realized I probably had a wrong conception of the meaning of hashable and immutable objects in python.
What ...
            
        
       
    
            99
            votes
        
        
            3
            answers
        
        
            47k
            views
        
    Immutable numpy array?
                Is there a simple way to create an immutable NumPy array?
If one has to derive a class from ndarray to do this, what's the minimum set of methods that one has to override to achieve immutability?
            
        
       
    
            97
            votes
        
        
            11
            answers
        
        
            40k
            views
        
    Why would one declare an immutable class final in Java?
                I read that to make a class immutable in Java, we should do the following,  
Do not provide any setters  
Mark all fields as private  
Make the class final
Why is step 3 required? Why should I mark ...
            
        
       
    
            97
            votes
        
        
            2
            answers
        
        
            14k
            views
        
    Isn't Redux just glorified global state?
                So I started learning React a week ago and I inevitably got to the problem of state and how components are supposed to communicate with the rest of the app. I searched around and Redux seems to be the ...
            
        
       
    
            96
            votes
        
        
            9
            answers
        
        
            13k
            views
        
    Building big, immutable objects without using constructors having long parameter lists
                I have some big (more than 3 fields) objects that can and should be immutable. Every time I run into that case I tend to create constructor abominations with long parameter lists. 
It doesn't feel ...
            
        
       
    
            95
            votes
        
        
            20
            answers
        
        
            69k
            views
        
    Why do we need immutable class?
                I am unable to get what are the scenarios where we need an immutable class.
Have you ever faced any such requirement? or can you please give us any real example where we should use this pattern.
            
        
       
    
            93
            votes
        
        
            12
            answers
        
        
            107k
            views
        
    In Python, how can I make unassignable attributes (like ones marked with `final` in Java)?
                Is there anything in Python that works like the final keyword in Java - i.e., to disallow assigning to a specific attribute of the instances of a class, after those instances have been created? I ...
            
        
       
    
            93
            votes
        
        
            14
            answers
        
        
            63k
            views
        
    Immutable class?
                How can one make a Java class immutable, what is the need of immutability and is there any advantage to using this?
            
        
       
    
            92
            votes
        
        
            7
            answers
        
        
            93k
            views
        
    Immutable/Mutable Collections in Swift
                I was referring to Apple's Swift programming guide for understanding creation of Mutable/ immutable objects(Array, Dictionary, Sets, Data) in Swift language. But I could't understand how to create a ...
            
        
       
    
            87
            votes
        
        
            8
            answers
        
        
            51k
            views
        
    In C#, why can't I modify the member of a value type instance in a foreach loop?
                I know that value types should be immutable, but that's just a suggestion, not a rule, right?
So why can't I do something like this:
struct MyStruct
{
    public string Name { get; set; }
}
 public ...
            
        
       
    
            86
            votes
        
        
            9
            answers
        
        
            39k
            views
        
    How can I create a new instance of ImmutableDictionary?
                I would like to write something like this:
var d = new ImmutableDictionary<string, int> { { "a", 1 }, { "b", 2 } };
(using ImmutableDictionary from System.Collections.Immutable). It seems like ...