If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, a set is an unordered collection of unique elements. Sets are defined by enclosing a comma-separated sequence of elements within curly braces
{ }
. Unlike lists and tuples, sets do not allow duplicate elements, and they do not maintain any particular order of the elements.Here's a brief introduction to sets in Python:
- Creating a Set: You can create a set by defining it with curly braces and including the elements separated by commas.
Example:
pythonCopy code
# Set of integers numbers_set = {1, 2, 3, 4, 5} # Set of strings fruits_set = {"apple", "banana", "orange"} # Mixed data types mixed_set = {10, "hello", 3.14, True}
- Accessing Elements: Since sets are unordered collections, you cannot access elements by index like in lists or tuples. Instead, you use sets primarily for membership testing and mathematical set operations.
Example:
pythonCopy code
fruits_set = {"apple", "banana", "orange"} print("apple" in fruits_set) # Output: True print("grape" in fruits_set) # Output: False
- Removing Duplicates: One of the primary uses of sets is to remove duplicates from other collections like lists.
Example:
pythonCopy code
numbers_list = [1, 2, 3, 3, 4, 4, 5, 5] unique_numbers_set = set(numbers_list) print(unique_numbers_set) # Output: {1, 2, 3, 4, 5}
- Set Operations: Sets support various mathematical set operations like union, intersection, difference, and symmetric difference.
Example:
pythonCopy code
set1 = {1, 2, 3} set2 = {3, 4, 5} # Union of two sets print(set1 | set2) # Output: {1, 2, 3, 4, 5} # Intersection of two sets print(set1 & set2) # Output: {3} # Difference of two sets print(set1 - set2) # Output: {1, 2} # Symmetric difference of two sets print(set1 ^ set2) # Output: {1, 2, 4, 5}
- Mutable Nature: Sets are mutable, which means you can add or remove elements after creating the set.
Example:
pythonCopy code
fruits_set = {"apple", "banana", "orange"} fruits_set.add("grape") # Add an element to the set print(fruits_set) # Output: {"apple", "banana", "orange", "grape"} fruits_set.remove("banana") # Remove an element from the set print(fruits_set) # Output: {"apple", "orange", "grape"}
Sets are useful when you need to perform operations like membership testing and eliminate duplicates from your data. They are also used for solving mathematical problems and dealing with unique elements in a collection. Keep in mind that the unordered nature of sets means that their elements are not indexed and they do not maintain any specific order.
Comments: 0