Sunday, October 22, 2017

set in python

#set doesnt have index , it contains unique values

>>> var
set([3, 1, 2, 'john'])

use update method to add multiple item to set
>>> var.update({5,6})
>>> var
set([1, 2, 3, 5, 6, 'john'])

use add to add single item to set
>>> var.add(9)
>>> var
set([1, 2, 3, 5, 6, 7, 9, 'john'])

remove item with 9 but gives error if 9 doesnt exist
>>> var.remove(9)
>>> var
set([1, 2, 3, 5, 6, 7, 'john'])

Use discard to delete 8 from set and it wont spit out error if it doesnt exist
var.discard(8)


# gives union of two sets
set1 | set 2
OR
set1.union(set2)

# gives difference
set1 - set2
OR
set1.difference(set2)

# things that is uniqe to a set
set1 ^ set2
or
set1.symmetric_difference(set2)
example:

>>> cd1={1,2,3,4}
>>> cd2={2,3,5,6}
>>> cd1 ^ cd2
set([1, 4, 5, 6])


# gives intersection
set1 & set2
set1.intersection(set2)

No comments:

Post a Comment