Sunday, June 11, 2017

Data Structures[] and their behavior in Python

Hi Learners,

Hope all are doing great.. !

I'm Python and Simple
HI folks lets Learn ME: Python
Here we go the Python's way of treating Data structures.

As everyone is aware, everythin in Python is treated as an Object,let it be a function, class, data structures.etc. we have different types of data representations in Python like
1.Numbers.
2.Strings

3.Sequenced datatypes
 3.1. Lists
 3.2. Tuples
 3.3. Dictionaries.
 3.4 Sets

1.Numbers:

Numbers incllude the types like Intgers, floats, Complex numbers.
Coming to the behavior of numbers in Python, these data types are treated as Immutable, so Increment and Decrement [++ and -- ] are not allowed in Python, as ++/-- work on the same object but numbers being immutable the object should be changed first and the increment is done later.
and the values when passed to a function they will be PASSED BY VALUES.Its a bad idea to use the word PASS BY VALUE in Python though.

The following example demonstrates the behavior well.
Example:
>>> def fun(x):
...     x=x+1
...     print(id(x))
...     print(x)
...
>>> x=10    ##Value outdside before calling fun
>>> print(id(x)) ##id before calling fun
1786819936
>>> fun(x)
1786819968 ##id inside the fun
11    ##Value inside the fun
>>> print(id(x)) #id after calling the fun
1786819936
>>> print(x)  #value after the fun
10

If you observe 'id(x)' and value of 'x' carefully, there is no change in the value and id, even after calling the fun(). It can be related to the pass by value concept of programming language like C.
But you have to accept the fact that if you are not working on the object inside the function the id(x) remains same.So its a bad convention to call it Pass by Value but the way it works force one to say it "PASS BY VALUE".



The same is applicable to "Strings" and Strings are immutble .

Example:
>>> def fun(x):
...     x=x+"Bhushan"
...     prind(id(x),":",x)
...
>>> def fun(x):
...     x=x+"Bhushan"
...     print(id(x),":",x)
...
>>> x="bharath"
>>> id(x)
1117227101016
>>> x
'bharath'
>>> fun(x)
1117227117872 : bharathBhushan
>>>

So PASS BY VALUE is assigned as Strings and Numbers are immutable.




No comments:

Post a Comment