Monday, July 20, 2015

Python- Set

Set – A Set in Python is a Un-ordered Collection of Unique and immutable Objects. The Set does not allow multiple occurrences of the same element.

A Set is created using the set() function available as

>>> x = set("A Python Tutorial")
>>> print x
set(['A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y', 'T'])
>>> type(x)
<type 'set'>

We can pass a list or Tuple to the Set as - x = set(["Perl", "Python", "Java"])

A tuple can be sent to Set as
>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))
>>> print cities
set(['Paris', 'Birmingham', 'Lyon', 'London', 'Berlin'])

But if we print the Tuple with Multiple similar elements, Set will take care of removing those. See the above example for the element “Paris”

Set are created in Such as way that they don’t allow mutable Objects in them.

>>> cities = set (["hai","bye"])
>>> print cities
set(['hai', 'bye'])
>>> cities = set ({"hai","bye"))
  File "<stdin>", line 1
    cities = set ({"hai","bye"))
SyntaxError: invalid syntax

Empty Set - Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument.

S = set()

Updating – Though Sets does not allow Mutable Objects, Sets are mutable objects as,

>>> cit=set(("hai","kai"))
>>> cit.add(("hello"))
>>> print cit
set(['hai', 'kai', 'hello'])

We can add single elements using the method add(). Multiple elements can be added using update() method. Theupdate() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.

Frozen Sets – Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.

Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary. Frozensets can be created using the function frozenset().

>>> cities = frozenset(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

No comments :

Post a Comment