Similarities between List and String¶
In [1]:
h_string = "hello"
h_list = list(h_string)
print(h_list)
In [2]:
print("h" in h_string)
print("h" in h_list)
In [3]:
print(h_string[0:3])
print(h_list[0:3])
In [4]:
for letter in h_string:
print(letter)
In [5]:
for letter in h_list:
print(letter)
Mutable vs Immutable datatypes¶
Lists are mutable. List values can be added, removed or changed. However, Strings are immutable. We cannot change a string value once it's created.
In [6]:
print(h_list)
h_list[3] = "f"
print(h_list)
print(h_string)
h_string[3] = "f"
print(h_string)
Referencing:¶
Whenever we create a mutable object, python just creates an object in the memory and store its memory reference to the given variable. Later, when we try to assign this variable to a new variable, python just link it to the old variable.
In [7]:
lang = ["R","java","c++","c"]
new_lang = lang
print("lang", lang)
print("new_lang",new_lang)
In [8]:
new_lang[0] = "Python"
print("new_lang",new_lang)
print("lang",lang)
Changing new_lang variable, also modifies lang variable value. This is not surprising becauses lists are mutable object, and it just stores a memory reference.
Note:¶
Generally, lists can contain large number of values, assume there are a billions of record in a list, and creating a new list while passing it to a function call will take a lot of extra time and space. So, instead of creating a new list, it simply passes the memory reference.tip: we can use copy.deepcopy to create a entire new list with new memory references.
In [9]:
import copy
lang = ["R","java","c++","c"]
new_lang = copy.deepcopy(lang)
lang[0] = "Python"
print("lang", lang)
print("new_lang",new_lang)
No comments :
Post a Comment