HackerRank Python Solution - Sets - .difference() operation

HackerRank Python Solution - Sets - .difference() operation
.difference():
  • The tool .difference() returns a set with all the elements from the set that are not in an iterable. Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in the set.
  • Set is immutable to the .difference() operation (or the - operation).

HackerRank Python Solution - Sets - .intersection() operation

HackerRank Python Solution - Sets - .intersection() operation
.intersection():
  • The .intersection() operator returns the intersection of a set and the set of elements in an iterable. Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in the set.
  • The set is immutable to the .intersection() operation (or & operation).

HackerRank Python Solution - Sets - .union() Operation

.union():
  • The .union() operator returns the union of a set and the set of elements in an iterable. Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set.
  • Set is immutable to the .union() operation (or | operation).

HackerRank Python Solution - Sets - .discard(), .remove() & .pop()

.remove(x):
  • This operation removes element x from the set.
  • If element x does not exist, it raises a KeyError.
  • The .remove(x) operation returns None.
Example:

>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.remove(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.remove(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.remove(0)
KeyError: 0

HackerRank Python Solution - Sets - .add()

  • If we want to add a single element to an existing set, we can use the .add() operation.
  • It adds the element to the set and returns 'None'.
Example:

>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...