Sets are indeed one of the four main built-in data types in Python designed for storing collections of data. The other three are Lists, Tuples, and Dictionaries, each with unique characteristics and uses.
Here are some corrections and additional insights about sets:
- Unordered: Sets are collections that do not record element position or order of insertion.
- Unchangeable: While sets themselves cannot be indexed or changed directly (elements cannot be accessed by an index or key), you can add new items or remove existing items.
- No Duplicates: Sets do not allow duplicate elements, which makes them ideal for membership testing, removing duplicates from a sequence, and computing mathematical operations like intersection, union, difference, and symmetric difference.
To access items in a Python set. Since sets are unordered and unindexed, you can’t access items by an index or a key like you would with lists or dictionaries. However, you can still interact with the items in a set through other methods:
Looping Through a Set: You can use a for
loop to iterate through each item in the set. Here’s an example from your slide:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
This will print each item in the set. Remember, the order of items when printed can vary because sets are unordered.
Checking for a Value: You can use the in
keyword to test if a specific item is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset) # Output: True
1. Using add()
The add()
method is used to add a single element to a set. This is useful when you want to include just one more item into an existing set.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
2. Using update()
The update()
method is used to add multiple items to a set. You can pass any iterable to this method, such as another set, list, tuple, etc.
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
To remove items from a set in Python, highlighting several methods and their behaviors. Here’s a breakdown of these methods based on your slide:
1. remove()
This method removes a specified element from the set. If the specified element does not exist in the set, it raises a KeyError
.
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset) # Output: {'apple', 'cherry'}
2. discard()
This method also removes a specified element from the set, but unlike remove()
, it does not raise an error if the element is not found.
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset) # Output: {'apple', 'cherry'}
# Using discard on an element not present in the set
thisset.discard("mango") # No error is thrown
print(thisset) # Output: {'apple', 'cherry'}
3. clear()
This method removes all elements from the set, resulting in an empty set.
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset) # Output: set()
4. Using del
While not a set method, del
is used to delete the set entirely. After deletion, the set no longer exists, so any attempt to use it will raise an error.
thisset = {"apple", "banana", "cherry"}
del thisset
# print(thisset) # This will raise an error because 'thisset' no longer exists
To loop through a set in Python. Here’s how the code works:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Explanation
- Set Definition:
thisset
is defined with three items:"apple"
,"banana"
, and"cherry"
. - Looping Through the Set: The
for
loop iterates over each element inthisset
. Since sets are unordered, the elements might be printed in any order, not necessarily the order in which they appear in the set.
Applying a Function to Each Item:
You can apply a specific function to each item in the set during the loop. For example, you might want to convert each item to uppercase:
for fruit in thisset:
print(fruit.upper())
Checking Conditions: If you want to check for a specific condition and perform actions based on it, you can incorporate conditionals inside your loop:
for fruit in thisset:
if fruit.startswith('a'):
print(fruit + " starts with 'a'")
Example 1: Removing Duplicates from a List
# Define a list with duplicates
my_list = [1, 2, 2, 3, 4, 4, 4, 5]
# Convert the list to a set to remove duplicates
my_set = set(my_list)
# Convert it back to a list (if you need a list format)
unique_list = list(my_set)
print(unique_list) # Output: [1, 2, 3, 4, 5]
Example 2: Set Operations (Union, Intersection, Difference)
# Define two sets
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union: elements appearing in either set
print(a | b) # Output: {1, 2, 3, 4, 5, 6}
# Intersection: elements appearing in both sets
print(a & b) # Output: {3, 4}
# Difference: elements in set a but not in set b
print(a - b) # Output: {1, 2}
# Symmetric Difference: elements in either set but not in both
print(a ^ b) # Output: {1, 2, 5, 6}
Example 3: Checking Membership
# Define a set
fruits = {"apple", "banana", "cherry"}
# Check if 'apple' is in the set
print("apple" in fruits) # Output: True
# Check if 'mango' is in the set
print("mango" in fruits) # Output: False
Example 4: Adding and Removing Elements
# Define a set
numbers = {1, 2, 3}
# Add an element
numbers.add(4)
print(numbers) # Output: {1, 2, 3, 4}
# Remove an element
numbers.remove(2)
print(numbers) # Output: {1, 3, 4}
Set part -2
Sets are indeed one of the built-in data types in Python used to store collections of data, along with lists, tuples, and dictionaries. Each of these types has unique qualities and uses.
Sets are particularly useful because they are unordered, do not allow duplicate elements, and provide efficient operations for checking membership, determining the number of elements, and performing mathematical operations like unions, intersections, and differences.
In your example:
thisset = {"apple", "banana", "cherry"}
print(thisset)
- Union of Sets:
set1.union(set2)
: Combines all elements fromset1
andset2
without duplicates.- Example Output:
{'a', 1, 2, 3, 'b', 'c'}
- Update Set:
set1.update(set2)
: Adds elements fromset2
toset1
, modifyingset1
.- Example Output:
{'a', 1, 2, 3, 'b', 'c'}
- Intersection Update:
x.intersection_update(y)
: Modifiesx
to keep only elements also found iny
.- Example Output:
{'apple'}
- Intersection:
z = x.intersection(y)
: Returns a new set containing only elements common to bothx
andy
.- Example Output:
{'apple'}
- Symmetric Difference Update:
x.symmetric_difference_update(y)
: Modifiesx
by removing elements found in both sets, and adding elements fromy
not inx
.- Example Output:
{'banana', 'cherry', 'google', 'microsoft'}
- Symmetric Difference:
z = x.symmetric_difference(y)
: Returns a new set with elements in eitherx
ory
but not in both.- Example Output:
{'banana', 'cherry', 'google', 'microsoft'}
Union of Sets
fruits = {'apple', 'banana', 'cherry'}
vegetables = {'carrot', 'potato', 'celery'}
# Combine fruits and vegetables into one set
combined = fruits.union(vegetables)
print(combined)
output:
{'banana', 'cherry', 'apple', 'carrot', 'potato', 'celery'}
Update Set
colors = {'red', 'blue', 'green'}
more_colors = {'orange', 'purple'}
# Add more colors to the original set
colors.update(more_colors)
print(colors)
Output:
{'red', 'blue', 'green', 'orange', 'purple'}
Intersection Update
even_numbers = {2, 4, 6, 8, 10}
primes = {2, 3, 5, 7}
# Keep only numbers that are both even and prime
even_numbers.intersection_update(primes)
print(even_numbers)
Output:
{2}
Intersection
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# Find common elements between set a and set b
common_elements = a.intersection(b)
print(common_elements)
Output:
{4, 5}
Symmetric Difference Update
classic_books = {'Pride and Prejudice', '1984', 'The Great Gatsby'}
modern_books = {'1984', 'The Road', 'The Fault in Our Stars'}
# Update classic_books with books that are not common
classic_books.symmetric_difference_update(modern_books)
print(classic_books)
Output:
{'Pride and Prejudice', 'The Great Gatsby', 'The Road', 'The Fault in Our Stars'}
Symmetric Difference
pets = {'dog', 'cat', 'parrot'}
wild_animals = {'lion', 'parrot', 'elephant'}
# Find animals that are not common between pets and wild animals
unique_animals = pets.symmetric_difference(wild_animals)
print(unique_animals)
Output:
{'dog', 'cat', 'lion', 'elephant'}
# Initial sets
fruits = {"apple", "banana", "cherry"}
colors = {"red", "blue", "green"}
numbers = {1, 2, 3, 4, 5}
more_numbers = {4, 5, 6, 7, 8}
primes = {2, 3, 5, 7}
# add()
fruits.add("orange")
print("After add():", fruits)
# Output: {'orange', 'cherry', 'apple', 'banana'}
# clear()
colors.clear()
print("After clear():", colors)
# Output: set()
# copy()
fruits_copy = fruits.copy()
print("After copy():", fruits_copy)
# Output: {'orange', 'cherry', 'apple', 'banana'}
# difference()
diff = numbers.difference(more_numbers)
print("After difference():", diff)
# Output: {1, 2, 3}
# difference_update()
numbers.difference_update(more_numbers)
print("After difference_update():", numbers)
# Output: {1, 2, 3}
# discard()
fruits.discard("banana")
print("After discard():", fruits)
# Output: {'orange', 'cherry', 'apple'}
# intersection()
inter = fruits.intersection({"apple", "mango"})
print("After intersection():", inter)
# Output: {'apple'}
# intersection_update()
fruits.intersection_update({"apple", "mango"})
print("After intersection_update():", fruits)
# Output: {'apple'}
# isdisjoint()
is_disjoint = numbers.isdisjoint(primes)
print("After isdisjoint():", is_disjoint)
# Output: True
# issubset()
is_subset = {1, 2}.issubset(numbers)
print("After issubset():", is_subset)
# Output: True
# issuperset()
is_superset = numbers.issuperset({1, 2})
print("After issuperset():", is_superset)
# Output: True
# pop()
popped_element = fruits_copy.pop()
print("After pop():", popped_element, fruits_copy)
# Output: apple {'orange', 'cherry', 'banana'} (popped element may vary)
# remove()
fruits_copy.add("banana") # Re-adding for demonstration
fruits_copy.remove("banana")
print("After remove():", fruits_copy)
# Output: {'orange', 'cherry'}
# symmetric_difference()
sym_diff = {1, 2, 3}.symmetric_difference({3, 4, 5})
print("After symmetric_difference():", sym_diff)
# Output: {1, 2, 4, 5}
# symmetric_difference_update()
a = {1, 2, 3}
b = {3, 4, 5}
a.symmetric_difference_update(b)
print("After symmetric_difference_update():", a)
# Output: {1, 2, 4, 5}
# union()
union_set = {1, 2, 3}.union({3, 4, 5})
print("After union():", union_set)
# Output: {1, 2, 3, 4, 5}
# update()
update_set = {1, 2, 3}
update_set.update({3, 4, 5})
print("After update():", update_set)
# Output: {1, 2, 3, 4, 5}
Dictionaries in Python -1
Dictionary Basics
A dictionary in Python is a collection of key-value pairs. Each key is unique and is used to store and retrieve the corresponding value. Dictionaries are ordered (as of Python 3.7), changeable, and do not allow duplicates.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Key Points about Dictionaries
- Ordered: Maintains the order of items (since Python 3.7).
- Changeable: Allows modification of items.
- Unique Keys: Each key must be unique; duplicate keys are not allowed.
Common Dictionary Operations
Accessing Items
brand = thisdict["brand"]
print(brand)
# Output: Ford
Adding or Changing Items
thisdict["color"] = "red" # Adding a new key-value pair
thisdict["year"] = 2020 # Changing the value of an existing key
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'red'}
Removing Items
thisdict.pop("model") # Removes the item with the specified key
print(thisdict)
# Output: {'brand': 'Ford', 'year': 2020, 'color': 'red'}
del thisdict["year"] # Removes the item with the specified key
print(thisdict)
# Output: {'brand': 'Ford', 'color': 'red'}
thisdict.clear() # Removes all items
print(thisdict)
# Output: {}
Looping Through a Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Loop through keys
for key in thisdict:
print(key)
# Output: brand, model, year
# Loop through values
for value in thisdict.values():
print(value)
# Output: Ford, Mustang, 1964
# Loop through key-value pairs
for key, value in thisdict.items():
print(key, value)
# Output: brand Ford, model Mustang, year 1964
Checking if a Key Exists
if "model" in thisdict:
print("Model is present.")
# Output: Model is present.
Dictionary Length
print(len(thisdict))
# Output: 3
Copying a Dictionary
copied_dict = thisdict.copy()
print(copied_dict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Nested Dictionaries
myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
},
"child3": {
"name": "Linus",
"year": 2011
}
}
print(myfamily)
# Output: {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Accessing a Specific Value by Key
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
# Output: Mustang
Using the get()
Method
x = thisdict.get("model")
print(x)
# Output: Mustang
Note: The get()
method is useful because it allows you to provide a default value if the key does not exist, preventing errors.
x = thisdict.get("color", "Not Found")
print(x)
# Output: Not Found
Getting All Keys
x = thisdict.keys()
print(x)
# Output: dict_keys(['brand', 'model', 'year'])
Getting All Values
x = thisdict.values()
print(x)
# Output: dict_values(['Ford', 'Mustang', 1964])
Getting All Key-Value Pairs
x = thisdict.items()
print(x)
# Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Additional Examples and Details
Looping Through Keys
for key in thisdict.keys():
print(key)
# Output:
# brand
# model
# year
The image provides examples of how to access items in a dictionary in Python. Here’s a detailed explanation of each method with examples:
Accessing Dictionary Items
- Accessing a Specific Value by KeypythonCopy code
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = thisdict["model"] print(x) # Output: Mustang
- Using the
get()
MethodpythonCopy codex = thisdict.get("model") print(x) # Output: Mustang
- Note: The
get()
method is useful because it allows you to provide a default value if the key does not exist, preventing errors.pythonCopy codex = thisdict.get("color", "Not Found") print(x) # Output: Not Found
- Note: The
- Getting All KeyspythonCopy code
x = thisdict.keys() print(x) # Output: dict_keys(['brand', 'model', 'year'])
- Getting All ValuespythonCopy code
x = thisdict.values() print(x) # Output: dict_values(['Ford', 'Mustang', 1964])
- Getting All Key-Value PairspythonCopy code
x = thisdict.items() print(x) # Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Additional Examples and Details
Looping Through Keys
Looping Through Values
pythonCopy codefor key in thisdict.keys():
print(key)
# Output:
# brand
# model
# year
for value in thisdict.values():
print(value)
# Output:
# Ford
# Mustang
# 1964
Looping Through Key-Value Pairs
for key, value in thisdict.items():
print(key, ":", value)
# Output:
# brand : Ford
# model : Mustang
# year : 1964
Checking if a Key Exists
if "model" in thisdict:
print("Model key exists")
# Output: Model key exists
Direct Assignment
- You can change the value of a specific key by directly assigning a new value to it.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Using the update()
Method
- The
update()
method allows you to update multiple items at once. You can pass a dictionary containing key-value pairs to update.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Adding Items to a Dictionary
- Direct Assignment
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Using the update()
Method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items from a Dictionary
- Using
pop()
Method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
# Output: {'brand': 'Ford', 'year': 1964}
Using popitem()
Method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang'}
Using del
Keyword
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
# Output: {'brand': 'Ford', 'year': 1964}
Using clear()
Method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
# Output: {}
Dictionaries in Python -2
Looping Through a Dictionary
- Loop Through Keys
- This will iterate through the keys of the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
# Output:
# brand
# model
# year
Loop Through Keys and Access Values
- This will iterate through the keys and access the corresponding values.
for x in thisdict:
print(thisdict[x])
# Output:
# Ford
# Mustang
# 1964
Loop Through Values
- This will iterate directly through the values of the dictionary
for x in thisdict.values():
print(x)
# Output:
# Ford
# Mustang
# 1964
Loop Through Key-Value Pairs
- This will iterate through the key-value pairs of the dictionary
for x, y in thisdict.items():
print(x, y)
# Output:
# brand Ford
# model Mustang
# year 1964
Copying a Dictionary
- Using the
copy()
Method- This method creates a shallow copy of the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Using the dict()
Constructor
- This method also creates a shallow copy of the dictionary by passing the original dictionary to the
dict()
constructor.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Creating a Nested Dictionary
- Directly Defining a Nested Dictionary
- This method involves defining the nested dictionary structure directly within the dictionary declaration.
myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
},
"child3": {
"name": "Linus",
"year": 2011
}
}
print(myfamily)
# Output:
# {
# 'child1': {'name': 'Emil', 'year': 2004},
# 'child2': {'name': 'Tobias', 'year': 2007},
# 'child3': {'name': 'Linus', 'year': 2011}
# }
Defining Nested Dictionaries Separately and Combining Them
- This method involves defining each nested dictionary separately and then combining them into a larger dictionary.
child1 = {
"name": "Emil",
"year": 2004
}
child2 = {
"name": "Tobias",
"year": 2007
}
child3 = {
"name": "Linus",
"year": 2011
}
myfamily = {
"child1": child1,
"child2": child2,
"child3": child3
}
print(myfamily)
# Output:
# {
# 'child1': {'name': 'Emil', 'year': 2004},
# 'child2': {'name': 'Tobias', 'year': 2007},
# 'child3': {'name': 'Linus', 'year': 2011}
# }
Dictionary Methods
- clear()
- Description: Removes all elements from the dictionary.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.clear()
print(thisdict)
# Output: {}
copy()
- Description: Returns a copy of the dictionary.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
mydict = thisdict.copy()
print(mydict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
fromkeys()
- Description: Returns a dictionary with the specified keys and value.
keys = ('key1', 'key2', 'key3')
value = 0
newdict = dict.fromkeys(keys, value)
print(newdict)
# Output: {'key1': 0, 'key2': 0, 'key3': 0}
get()
- Description: Returns the value of the specified key.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
model = thisdict.get("model")
print(model)
# Output: Mustang
items()
- Description: Returns a list containing a tuple for each key-value pair.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
items = thisdict.items()
print(items)
# Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
keys()
- Description: Returns a list containing the dictionary’s keys.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
keys = thisdict.keys()
print(keys)
# Output: dict_keys(['brand', 'model', 'year'])
pop()
- Description: Removes the element with the specified key.
pop()
Description: Removes the element with the specified key.
popitem()
- Description: Removes the last inserted key-value pair.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.popitem()
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang'}
setdefault()
- Description: Returns the value of the specified key. If the key does not exist, inserts the key with the specified value.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
color = thisdict.setdefault("color", "red")
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
update()
- Description: Updates the dictionary with the specified key-value pairs.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.update({"color": "red"})
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
values()
- Description: Returns a list of all the values in the dictionary.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
values = thisdict.values()
print(values)
# Output: dict_values(['Ford', 'Mustang', 1964])