Majorly used Data Structures in python are as follows:
- List
- Set
- Tuple
- Dictionary
- String
- Numbers(int, float, decimal)
One of the major things in python discussed is whether the data structure is mutable or immutable.
What do this terms mean?
In simple terms, Immutable means value cannot be changed after it is assigned to a variable.
Whereas, In mutable data type value can be changed after assignment.
Hmm, What ??? This is still not clear these are merely dictionary definitions I am blabbering.
Ok ok, So let's look at this by example.
Fire up your python shell and type following:
>>> X = Y = [1,2,3]
# This means X and Y are pointing to some list stored at some memory.
Now we change X.
X.append(4)
print (X)
print (Y)
# Both same right ??
This means List is a Mutable data structure. When we altered X it went on to change List stored at memory XXXX. Hence the change is reflected when we accessed Y variable.
Now, let's take a similar example with Strings:
string1 = string2 = "Hello"
#Now we go to alter one of them.
string1 = "Hello how are you ?"
print (string1)
print (string2)
# Woah Both different right ??
What does this mean??
This means String is an Immutable data structure. When we altered "string1" it went on to create new string at new memory location YYYY and allocate it to "string1". Hence the change is not reflected when we accessed "string2" variable because it is still pointing to original memory location value.
Ok So how to confirm this memory locations thing?
In python you can check memory location of a variable by following :
>>> hex(id(variable_name_here))
So let's go back to the shell and check the memory locations too now along with changes.
string1 = string2 = "Hello"
# Now we are checking their memory locations.
'0x7ff9313525a8'
>>> hex(id(string2))
'0x7ff9313525a8'
#Both are pointing to the same memory location hence same value given by both.
#Now we go to alter one of them.
string1 = "Hello how are you ?"
'0x7ff931352650'
>>> hex(id(string2))
'0x7ff9313525a8'
print (string1)
print (string2)
Hope this helped.
Immutable data structures:
- bool
- string
- tuple
- list
- dictionary
- set
- user-defined classes (unless specifically made immutable)
If you are a newbie in python, Some books you can read are:
Two Scoops of Django 1.11: Best Practices for the Django Web Framework
Please share and comment if anything is missing or wrong. I am newbie blogger so please support me. :)
Comments
Post a Comment