Python
  • Getting Started
    • Input and Output
    • Variables
    • Data Types
    • Conditional Structures
      • Humidity Level
      • Financial Transactions
      • Fruit-Vending Machine
      • Magic While
      • FizzBuzz
    • Functions
      • Hashtag Generator
  • Data Structures
    • Lists
    • Dictionary
    • Set
    • Interpreter Expressions
  • OOPs
    • Classes and Objects
    • Exception Handling
      • Simple Calculator
  • System Programming
    • File Operations
    • Directory Navigation
    • Process Creation
    • Threads
Powered by GitBook
On this page
  • How to Create Sets
  • Methods to Change a Set
  • Few more Set Methods
  1. Data Structures

Set

I LOVE DOING THIS :)

A set is an unordered collection data type with No Duplicate elements, they are Iterable and Mutable.

The elements appear in an arbitrary order when sets are iterated

Sets are commonly used for removing duplicates entries, and also for operations such as intersection, union, and set difference

How to Create Sets

Sets can be created by calling the built-in set() function with a sequence

>>> d0p = set()
>>> print(d0p)
set([])
>>>
>>> d0p = set("Akash")
>>> set(['A', 'a', 'k', 's', 'h'])

Creating a set with a list []

>>> d0p = set(["bikes","cars","books"])
>>> print(d0p)
set(['cars', 'bikes', 'books'])

Creating a set with numbers and seeing how it strips away the duplicates

>>> d0p = set([1, 2, 3, 4, 5, 6, 7, 7, 7])
>>> print(d0p)
set([1,2,3,4,5,6,7])

Creating a set with strings and removing the duplicates

>>> mystring = "Akash Kannan"
>>> d0p = set(mystring)
>>> print(d0p)
set(['A', 'a', ' ', 'h', 'k', 'n', 's', 'K'])

Methods to Change a Set

Add elements to a Set

>>> d0p = set([1, 2, 3, 4, 5, 6, 7])
>>> d0p.add(8)
>>> print(d0p)
set([1, 2, 3, 4, 5, 6, 7, 8])

We can add a tuple (9, 10) to the d0p and the new set will consist of the tuple

>>> d0p = set([1, 2, 3, 4, 5, 6, 7, 8])
>>> d0p.add((9,10))
>>> print(d0p)
set([1, 2, 3, 4, 5, 6, 7, 8, (9,10)])

Similarly, we can update our current set using d0p.update([11, 12])

We can literally update our set using a list or tuple or a dictionary too

Remove elements from a Set

We can remove an element from the set using these two methods called .discard and .remove

>>> d0p = set([1, 2, 3, 4, 5, 6, 7, 8])
>>> d0p.discard(2)
>>> d0p.remove(3)
>>> print(d0p)
set([1, 4, 5, 6, 7, 8])

The only key difference between discard and remove is that discard doesn't throw any error if the element isn't present but whereas remove will raise a KeyError Exception

Few more Set Methods

  • copy() - Creates a shallow copy of the set with which it is called

>>> d0p = set([1, 2, 3, 4, 5, 6, 7, 8])
>>> d0p_copy = d0p.copy()
>>> print(d0p_copy)
set([1, 2, 3, 4, 5, 6, 7, 8])
  • pop() - Removes an arbitrary set element

  • clear() - Will remove all the elements in the set

PreviousDictionaryNextInterpreter Expressions

Last updated 2 years ago