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

>>> ‘mango’ in fruit

>>> ‘grape’ in fruit

>>> a = (‘abhilash’)

>>> a

>>> b = (‘abhijith’)

>>> b

>>> 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’])


Author: Abhi

Hi, this is Abhilash - Senior Programmer Analyst at CoMakeIT, specialised on web programming. Mainly working on Ruby On Rails platform since 2010.

Leave a Reply

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

You are commenting using your 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