Why Are Python List Operations/Methods Unlike Python String Operations/Methods?

Problem scenario
List operations such as .sort() will change previous copies of the list.

String operations such as .replace("old_pattern", "new_pattern", count), will not change the variable or its copies; these operations will return a string after the replace operation has run on the original string.

Why is this behavior happening?

In-place changes and mutability are factors. Strings are generally immutable whereas copies of lists are usually shallow.

program1.py shows how lists are mutable with inplace changes happening to a copy; program2.py shows how strings are immutable and have no inplace changes to them when the .replace method is used.

# Filename: program1.py

one_list = ['dog', 'cat', 'horse', 'cow']
print("Above is one_list before modifications have happened.")
copy_of_list = one_list
print("The one_list was modified earlier in the execution of this program.")
print("The one_list is above and the copy_list is below")
print("The .append and .sort methods change copies of the string in addition to the string itself.")
print("You may want to use deep copies instead of shallow copies if you don't want copies to be modified with the original.")

# Filename: program2.py:

first_string = "aaaaaaaaaaaaaaaaaabcdefgh"
second_string = first_string.replace('a', 'z', -1)
print("The replace method was invoked earlier in the execution of this program.")
print(" ")
print("first_string is above; second_string is below")

print("Now you can see how the .replace method only emphemerally returns a string after operating on it.")
print("The .replace method does not change the string it operates on.  The operations can be saved to a new variable if you want to use .replace.")

The replace method of a string does not modify the variable it operates on. It returns the modified string. With list manipulations, the copy of the list can be changed (unless you copy like this new_list = old_list[:]).

Leave a comment

Your email address will not be published. Required fields are marked *