set

 A set in Python is an unordered, mutable collection of unique elements. It does not allow duplicate values and is commonly used for mathematical set operations like union, intersection, and difference.


Key Characteristics of Sets:


✅ Unordered – Elements do not maintain a specific order.

✅ Mutable – You can add or remove elements.

✅ Unique Elements – No duplicate values allowed.

✅ No Indexing – Cannot access elements using an index.




# Creating sets

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

print(number)

print(type(number))


# Sets ignore duplicate values

newnumber = {1, 2, 3, 4, 5, 4, 3, 2, 2, 1, "tt"}

print(newnumber)


# Adding an element

newnumber.add("Praveen")

print(newnumber)


# Merging two sets

thisset = {"apple", "banana", "cherry"}

tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)


# Merging a list into a set

thisset = {"apple", "banana", "cherry"}

mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)


# Removing an element using remove()

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)


# Removing an element using discard()

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)


# Removing a random element using pop()

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)  # Prints the removed element

print(thisset)


# Clearing all elements from a set

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)  # Output: set()


# Deleting the set completely

thisset2 = {"apple", "banana", "cherry"}

del thisset2

# print(thisset2)  # Uncommenting this will raise an error: NameError

Comments

Popular posts from this blog

Mastering Django: Project and App Folder Structure

Mastering Django Template Language (DTL): A Step-by-Step Guide

How to Add Templates in Django: Step-by-Step Guide