What is Python Sets and how to use it?
- Get link
- X
- Other Apps
In Python, a set is an unordered collection of unique elements. This means that a set does not allow duplicate items, and the elements are not stored in any particular order. Sets are mutable, meaning you can add or remove elements, but the elements themselves must be immutable (like strings, numbers, or tuples).
### Creating Sets
You can
create a set by placing items inside curly braces `{}`, separated by commas, or
by using the `set()` function.
```python
# Creating a
set with curly braces
fruits =
{"apple", "banana", "cherry"}
# Creating a
set using the set() function
numbers =
set([1, 2, 3, 4, 5])
# Creating
an empty set (Note: you must use set(), {} creates an empty dictionary)
empty_set =
set()
```
###
Properties of Sets
-
**Unordered**: Elements in a set do not have a specific order.
- **No
Duplicates**: A set cannot contain duplicate elements; any duplicate items are
automatically removed.
```python
# Example of
no duplicates in a set
my_set = {1,
2, 2, 3, 4, 4}
print(my_set) # Output: {1, 2, 3, 4}
```
### Accessing
Set Items
Since sets are unordered, you cannot access items by index or slice a set. However, you can iterate over the elements of a set using a `for` loop.
```python
for fruit in
fruits:
print(fruit)
# Output
(order may vary):
# apple
# banana
# cherry
```
### Adding
and Removing Items
You can
modify a set by adding or removing elements.
-
**`add()`**: Adds a single element to the set.
```python
fruits.add("orange")
print(fruits)
# Output: {"apple", "banana", "cherry",
"orange"}
```
- **`update()`**:
Adds multiple elements to the set. You can pass any iterable (list, set, tuple,
etc.).
```python
fruits.update(["mango",
"grape"])
print(fruits)
# Output: {"apple", "banana", "cherry",
"orange", "mango", "grape"}
```
-
**`remove()`**: Removes a specific element from the set. Raises a `KeyError` if
the element is not found.
```python
fruits.remove("banana")
print(fruits)
# Output: {"apple", "cherry", "orange",
"mango", "grape"}
```
-
**`discard()`**: Removes a specific element from the set, but does not raise an
error if the element is not found.
```python
fruits.discard("banana") # No error, even though "banana" is
not in the set
```
-
**`pop()`**: Removes and returns an arbitrary element from the set. Since sets
are unordered, you don't know which item will be removed.
```python
removed_item = fruits.pop()
print(removed_item) # Output: (an arbitrary element from the set)
```
-
**`clear()`**: Removes all elements from the set.
```python
fruits.clear()
print(fruits)
# Output: set()
```
### Set
Operations
Sets are
particularly useful for performing mathematical operations like union,
intersection, difference, and symmetric difference.
- **Union
(`|` or `union()`)**: Combines all elements from two sets, removing duplicates.
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
# or using union()
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
```
- **Intersection
(`&` or `intersection()`)**: Returns the elements that are common in both
sets.
```python
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
# or using intersection()
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
```
-
**Difference (`-` or `difference()`)**: Returns the elements that are in the
first set but not in the second.
```python
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}
# or using difference()
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
```
- **Symmetric Difference (`^` or `symmetric_difference()`)**: Returns the elements that are in either set, but not in both.
```python
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
# or using symmetric_difference()
symmetric_difference_set =
set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
```
### Set Methods
In addition
to the above operations, sets have several useful methods:
-
**`issubset()`**: Returns `True` if all elements of the set are in another set.
```python
print(set1.issubset(union_set)) # Output: True
```
-
**`issuperset()`**: Returns `True` if the set contains all elements of another
set.
```python
print(union_set.issuperset(set1)) # Output: True
```
-
**`copy()`**: Returns a shallow copy of the set.
```python
new_set = set1.copy()
print(new_set) # Output: {1, 2, 3}
```
### Frozen Sets
A
**frozenset** is an immutable version of a set. Once created, a frozenset
cannot be modified (you cannot add, remove, or change elements). This is useful
when you need a set to be constant and hashable (e.g., as keys in a dictionary).
```python
frozen_set =
frozenset([1, 2, 3])
print(frozen_set) # Output: frozenset({1, 2, 3})
# Trying to
modify a frozenset will raise an error
#
frozen_set.add(4) # AttributeError:
'frozenset' object has no attribute 'add'
```
###
Conclusion
Python sets
are a powerful tool for managing collections of unique elements. They are
particularly useful for operations involving multiple collections, such as
finding common elements or differences between sets. Understanding how to use
sets effectively will help you write more efficient and clear Python code,
especially when dealing with tasks that require uniqueness or set operations.
- Get link
- X
- Other Apps
Popular posts from this blog
Top international payment gateway transaction fee comparison (2024)
How to Manage Boot Configuration of Windows using CMD
How to Get Inverse of a Matrix in Excel
Free Source Code and Documentation for Android App, Free for Commercial and non commercial purpose.
- Source Code with Documentation for Android Web shortcut key app Free Download
- Source Code with Documentation for Android VPN App Free Download
- Source Code with Documentation for Android Screen Recorder App Free Download
- Source Code with Documentation for Android Love calculator App Free Download
- Source Code with Documentation for Android Kids Math IQ App Free Download
- Source Code with Documentation for Android Diet Plan App Free Download
- Source Code with Documentation for Android BMI Calculator App Free Download
- Source Code with Documentation for Android Blogger App Free Download (Admin and Client App) Make a blogpost