Sunday, August 29, 2010

Programming in Python : Sets

Set is a data type in python. It is an unordered set of elements without duplicates. We can test an element is a member of the set. Set operations can operate on unique letters as given below.

>>> list1 = ['apple','mango','pineapple','mango','apple','orange']

>>> fruit = set(list1)

>>> fruit
set(['orange','mango','apple','pineapple'])

>>> 'mango' in fruit
True

>>> 'grape' in fruit
False

>>> a = ('abhilash')

>>> a
'abhilash'

>>> b = ('abhijith')

>>> b
'abhijith'

>>> set(a)
set(['a', 'b', 'i', 'h', 'l', 's'])

>>> set(b)
set(['a', 'b', 'i', 'h', 'j', 't'])

>>> c = set(a)

>>> d = set(b)

>>> c
set(['a', 'b', 'i', 'h', 'l', 's'])

>>> d
set(['a', 'b', 'i', 'h', 'j', 't'])

>>> c-d
set(['s', 'l'])

>>> d-c
set(['j', 't'])

>>> c |d
set(['a', 'b', 'i', 'h', 'j', 'l', 's', 't'])

>>> c & d
set(['a', 'i', 'b', 'h'])

>>> c ^ d
set(['s', 't', 'j', 'l'])

No comments:

Post a Comment