Python bits and bytes

Often we read lots of things from internet and learn but as time passes ,we do not use those learning in our daily life and we tend to forget those things which we have learnt earlier .So i thought it would be nice if put some good stuff her on  this blog .

Lets start something interesting python snippet.

Python immutable and mutable debate –

  • Tuples ,int,float,string ,frozensets,bytes are immutable in python.
  • list,set ,dict ,bytearray are mutable

bytes , bytearray frozensets new to you ???? follow this link bytearray

Sets are implemented in a way, which doesn't allow mutable objects. The following example demonstrates that we cannot include for example lists as elements:
>>> cities = set( ( ("Python","Perl"), ("Paris", "Berlin", "London") ) )
>>> cities = set( ( ["Python","Perl"], ["Paris", "Berlin", "London"] ) )
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list
So set can not allow unhashable type.Though sets can't contain mutable objects, sets are mutable 

>>> cities = set(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
>>> cities
{'Freiburg', 'Basel', 'Frankfurt', 'Strasbourg'}


Frozensets are like sets except that they cannot be changed, i.e. they are immutable:
>>> cities = frozenset(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'frozenset' object has no attribute 'add'

Is mutability really matters ?  Yes, it matters.

Follow some code snippets in the link mutable/non-mutable,what is actually immutable

.

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s