StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Set
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
dict (Dictionary) : Frozenset
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

A set in Python is an unordered collection of unique items. It is a mutable data type, meaning you can add and remove items from it after it has been created. Sets are created by placing comma-separated items inside curly braces {} or by using the set() constructor.


Key Characteristics of Sets

  • Unordered: Unlike lists or tuples, sets do not maintain the order in which items are inserted. When you print a set, the items may appear in a different order each time.

  • Unique Elements: Sets automatically enforce uniqueness. If you try to add an item that is already in the set, the set will not change. This makes them very useful for tasks like removing duplicates from a list.

  • Mutable: You can add and remove items from a set.

  • Items Must be Immutable: The items within a set must be of an immutable data type (like numbers, strings, or tuples). You cannot have a list or another set as an item within a set.


Set Operations

The most powerful feature of sets is their ability to perform mathematical set operations efficiently.

  • Union (| or .union()): Returns a new set containing all the unique items from both sets.

  • Intersection (& or .intersection()): Returns a new set containing only the items that are present in both sets.

  • Difference (- or .difference()): Returns a new set containing items that are in the first set but not in the second set.

  • Symmetric Difference (^ or .symmetric_difference()): Returns a new set containing items that are in either of the sets, but not in both.


Common Set Methods

Methods are functions called on a set object itself (e.g., my_set.add()).

Adding and Removing Items

  • .add(item): Adds a single item to the set.

  • .update(iterable): Adds all the items from an iterable (like a list or another set) to the set.

  • .remove(item): Removes a specified item. It will raise a KeyError if the item is not found.

  • .discard(item): Removes a specified item, but it will not raise an error if the item is not found.

  • .pop(): Removes and returns an arbitrary item from the set.

  • .clear(): Removes all items from the set.


Built-in Functions for Sets

  • len(): Returns the number of items in a set.

  • sum(): Returns the sum of all items (if they are all numbers).

  • min() / max(): Returns the minimum or maximum item.

  • sorted(): Returns a new, sorted list of the items in the set.

 

# --- 1. Set Creation ---

# Sets are unordered collections of unique items in curly braces.

empty_set = set() # Note: {} creates an empty dictionary, not a set.

fruits_set = {"apple", "banana", "cherry", "apple"} # Duplicates are automatically removed.

 

print(f"A set of fruits: {fruits_set}")

 

# --- 2. Adding and Removing Elements ---

print("\n--- Adding and Removing Elements ---")

# .add() adds a single element.

fruits_set.add("orange")

print(f"After .add('orange'): {fruits_set}")

 

# .update() adds multiple elements from an iterable.

fruits_set.update(["mango", "grape", "banana"])

print(f"After .update(['mango', 'grape', 'banana']): {fruits_set}")

 

# .remove() removes an element (raises an error if not found).

fruits_set.remove("banana")

print(f"After .remove('banana'): {fruits_set}")

 

# .discard() removes an element (does not raise an error).

fruits_set.discard("kiwi") # 'kiwi' is not in the set, but no error occurs.

print(f"After .discard('kiwi'): {fruits_set}")

 

# .pop() removes and returns an arbitrary element.

popped_fruit = fruits_set.pop()

print(f"Popped item: {popped_fruit}, Set is now: {fruits_set}")

 

# --- 3. Set Operations ---

set_a = {1, 2, 3, 4, 5}

set_b = {4, 5, 6, 7, 8}

print("\n--- Set Operations ---")

print(f"Set A: {set_a}")

print(f"Set B: {set_b}")

 

# Union (|): All unique elements from both sets.

print(f"Union (A | B): {set_a | set_b}")

 

# Intersection (&): Elements that are in both sets.

print(f"Intersection (A & B): {set_a & set_b}")

 

# Difference (-): Elements in A but not in B.

print(f"Difference (A - B): {set_a - set_b}")

 

# Symmetric Difference (^): Elements in either A or B, but not both.

print(f"Symmetric Difference (A ^ B): {set_a ^ set_b}")

 

# --- 4. Set Methods for Operations ---

# These methods are an alternative way to perform the operations above.

print("\n--- Set Methods for Operations ---")

print(f"A.union(B): {set_a.union(set_b)}")

print(f"A.intersection(B): {set_a.intersection(set_b)}")

 

# --- 5. Membership Testing ---

# Checking if an item is in a set is very fast.

print("\n--- Membership Testing ---")

print(f"Is 3 in Set A? {3 in set_a}")

print(f"Is 10 not in Set A? {10 not in set_a}")

 

# --- 6. Built-in Functions with Sets ---

print("\n--- Built-in Functions with Sets ---")

numbers_set = {5, 2, 8, 1, 9}

print(f"Length of numbers_set: {len(numbers_set)}")

print(f"Sum of numbers_set: {sum(numbers_set)}")

print(f"Max of numbers_set: {max(numbers_set)}")

print(f"Min of numbers_set: {min(numbers_set)}")

 

# sorted() returns a new sorted LIST, not a set.

sorted_list_from_set = sorted(numbers_set)

print(f"Original set: {numbers_set}")

print(f"New sorted list from set: {sorted_list_from_set}")

 

dict (Dictionary) Frozenset
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website