Monday, December 26, 2016

List and String Similarities in Python


Similarities between List and String

In [1]:
h_string = "hello"
h_list = list(h_string)
print(h_list)
['h', 'e', 'l', 'l', 'o']
In [2]:
print("h" in h_string)
print("h" in h_list)
True
True
In [3]:
print(h_string[0:3])
print(h_list[0:3])
hel
['h', 'e', 'l']
In [4]:
for letter in h_string:
    print(letter)
h
e
l
l
o
In [5]:
for letter in h_list:
    print(letter)
h
e
l
l
o

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)
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'f', 'o']
hello
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-a9a37efc26ee> in <module>()
      4 
      5 print(h_string)
----> 6 h_string[3] = "f"
      7 print(h_string)

TypeError: 'str' object does not support item assignment

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)
lang ['R', 'java', 'c++', 'c']
new_lang ['R', 'java', 'c++', 'c']
In [8]:
new_lang[0] = "Python"
print("new_lang",new_lang)
print("lang",lang)
new_lang ['Python', 'java', 'c++', 'c']
lang ['Python', 'java', 'c++', 'c']
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)
lang ['Python', 'java', 'c++', 'c']
new_lang ['R', 'java', 'c++', 'c']

No comments :

Post a Comment