Skip to content

Latest commit

Β 

History

History
468 lines (256 loc) Β· 10.3 KB

z_set_function().md

File metadata and controls

468 lines (256 loc) Β· 10.3 KB

🟑 SET



🟦 set function in Python is used to create a set, which is a built-in data type representing an unordered collection of unique elements.


🟠 Here's a brief explanation and a list of methods or functions similar to set, including their purposes:


Similar Methods or Functions

🟧 list(iterable):


    • Purpose: Creates a list object from an iterable. Unlike sets, lists can contain duplicate elements and maintain the order of elements. tuple(iterable):
    • Purpose: Creates a tuple object from an iterable. Tuples are similar to lists but are immutable, meaning their contents cannot be changed once created. frozenset(iterable):
    • Purpose: Creates an immutable version of a set. Frozensets are hashable and can be used as dictionary keys or elements of other sets, but you cannot modify their contents after creation. dict(iterable):
    • Purpose: Creates a dictionary object from an iterable of key-value pairs.
    • Dictionaries store data in key-value pairs and do not allow duplicate keys.

collections.Counter(iterable):


    • Purpose: βœ‹ Creates a Counter object, which is a specialized dictionary subclass for counting hashable objects.
    • It counts the frequency of elements in an iterable and can be used for various counting and frequency operations.

collections.defaultdict(default_factory):

    • Purpose: Creates a dictionary with a default value for non-existent keys. This allows for automatic handling of missing keys with a specified default factory function. setdefault(key, default) (method of dictionaries):
    • Purpose: Retrieves the value for the given key if it exists in the dictionary; otherwise, it sets the key with a default value and returns that default value. Each of these functions and methods has its specific use cases, but they all deal with creating or manipulating collections of data in various ways.

🟠 Common Operations

my_set = set([1, 2, 3]) # CREATES set
my_set.add(4)               # ADDING ELEMENTS: Adds 4 to the set
my_set.remove(2)            # REMOVE ELEMENTS: Removes 2 from the set
print(3 in my_set)          # Prints True

🫐 More Operations

  • Popping elements
my_set = {1, 2, 3}
element = my_set.pop()  # Removes and returns an arbitrary element
print(element)          # Output could be 1, 2, or 3
print(my_set)           # Output will be the set without the popped element
  • clearing elements
my_set = {1, 2, 3}
my_set.clear()  # Removes all elements from the set
print(my_set)   # Output: set()
  • Copying a set
my_set = {1, 2, 3}
new_set = my_set.copy()  # Creates a shallow copy of the set
print(new_set)           # Output: {1, 2, 3}
  • SET Length
my_set = {1, 2, 3}
print(len(my_set))  # Output: 3


🟦 Set Operations

🟧 Union

    • The | operator or the union() method is used to merge two sets and automatically handle duplicates.

Here’s a quick breakdown:


# merging, will ignore the duplicates
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # or set1.union(set2)
print(union_set)         # Output: {1, 2, 3, 4, 5}

  • The | operator is known as the "bitwise OR" operator in many programming languages. When used with sets in Python, it performs a union operation, combining all unique elements from both sets.

βœ‹In the context of bitwise operations, | operates on the individual bits of integer values, performing a bitwise OR. However, when applied to sets, it is used to compute the union of those sets.


πŸ”΄ NOT TO CONFUSE with the || OR operator from javascript, that one is used for boolean logic, evaluating to true if at least one of its operands is true.

    • For non-boolean values, it returns the first truthy value or the last value if none are truthy.

read More here z_Bitwise_operator





🟑 Mongo

🟣 QUESTION: I know that MongoDB has a set method. How does Python handle similar functionality?


βœ… Chatgpt:

    • In MongoDB, the set operator is used within update operations to specify the value of a field or to add new fields to a document. The functionality and purpose of the set operator in MongoDB are quite different from the set function in Python.


🟦 Key Differences

Purpose:


Python set: Used for creating a collection of unique items in memory.

MongoDB $set: Used for updating or adding fields in database documents.


🟧 Functionality:


Python set: Creates and manipulates a collection of unique items.

MongoDB $set: Modifies or adds fields in database documents.


Despite their similar names, the MongoDB $set operator and Python’s set function πŸ”΄ serve very different purposes and operate in different contexts.


πŸ’ pymongo

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']

# Example Python set βœ‹ SET python
unique_values = set([1, 2, 3, 2, 1])  # This will be {1, 2, 3}

# Prepare a MongoDB update operation using the $set operator
update_query = { '_id': 1 }
# βœ‹ SET mongo
update_values = { '$set': { 'unique_values': list(unique_values) } }

# Update the MongoDB document
collection.update_one(update_query, update_values)

# Fetch and print the updated document
document = collection.find_one({'_id': 1})
print(document)

🌴 MONGO: 🌞 $set

$set is used to modify data within a MongoDB collection.

πŸ”΄ They interact with different parts of your application and don't interfere with each other.



🟦 Scenario


  • Suppose you have a MongoDB collection named users, and you want to update the address of a user with a specific user_id.

  • πŸ”Έ The $set operator will be used to update the address field in the user's document.


Setup

MongoDB Collection Setup:

    • Assume your MongoDB collection users has the following documents:
{
  "_id": 1,
  "name": "Alice",
  "address": "123 Old St"
},
{
  "_id": 2,
  "name": "Bob",
  "address": "456 New Ave"
}


🟠 Python Script to UPDATE the address propery:

This script connects to MongoDB, updates a document using $set, and then retrieves and prints the updated document.


from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['users']

# Update the user's address using $set
user_id_to_update = 1
new_address = "789 Updated Blvd"
update_query = { '_id': user_id_to_update }
update_values = { '$set': { 'address': new_address } }

# Perform the update operation
result = collection.update_one(update_query, update_values)

# Fetch and print the updated document
updated_document = collection.find_one({ '_id': user_id_to_update })
print(updated_document)

output

  • Assuming the script runs successfully, here’s what you would expect the output to look like:
{
  "_id": 1,
  "name": "Alice",
  "address": "789 Updated Blvd"
}

🟦 Explanation

Update Operation:

Query: { '_id': 1 } specifies which document to update (the document with _id equal to 1).

Update: { '$set': { 'address': '789 Updated Blvd' } } specifies the change to be made, which is updating the address field.

Fetch Updated Document:

After performing the update, the find_one method retrieves the updated document based on the _id.

This example demonstrates how MongoDB's $set operator is used to modify an existing field in a document.

  • The Python script connects to the MongoDB database, performs the update, and then retrieves the updated document to confirm the change.


🟑 Javascript


🟣 QUESTION: So this set method in Python is similar to the set method in JavaScript


βœ… Chatgpt:

  • Yes, Python's set and JavaScript's Set share some similarities in terms of their core functionality, but there are differences in their syntax and usage. Here’s a comparison of the two:

🌈 Python set

    • Purpose: Represents an unordered collection of unique elements. It is a built-in data type in Python.
# When you create a set in Python using the set() constructor, it automatically removes duplicate elements. This is because a set is designed to hold only unique items.
my_set = set([1, 2, 3, 2, 1])  # {1, 2, 3}

🟧 Here's what's happening:


    • You start with a list that contains duplicate elements: [1, 2, 3, 2, 1].
    • When you convert this list to a set using set([1, 2, 3, 2, 1]), the set automatically removes the duplicates.
    • As a result, my_set will contain only the unique elements {1, 2, 3}


🌈 JavaScript Set

    • Purpose: Represents a collection of unique values. It is a built-in object in JavaScript.
let mySet = new Set([1, 2, 3, 2, 1]);  // Set {1, 2, 3}

Key Operations:


πŸ”΄Set Operations: JavaScript does not natively support set operations like union, intersection, and difference directly.


Adding an Element: mySet.add(4)

Removing an Element: mySet.delete(2)


let mySet = new Set([1, 2, 3]);
mySet.add(4);               // Adds 4 to the set
mySet.delete(2);            // Removes 2 from the set
console.log(mySet.has(3));  // Prints true

Checking Membership: mySet.has(4) returns true or false


# βœ‹ In JavaScript, you can use the has() method to check if a value is present in a Set. Here’s how you can use it:
# Creating a set
// Creating a Set
const mySet = new Set([1, 2, 3, 4, 5]);

// Checking membership
const elementToCheck = 4;

// Using 'has()' to check if the element is in the Set
const isMember = mySet.has(elementToCheck);

// Printing the result
console.log(isMember);  // Output will be true if 4 is in the Set, otherwise false


#
# βœ‹ output
# true
#

mySet is a Set containing the numbers 1, 2, 3, 4, 5.

The has() method checks if 4 is an element in mySet.