tg-me.com/python_codes/252
Create:
Last Update:
Last Update:
Common techniques for using the set() function in Python:
1. Create a set from a list:
my_list = [1, 2, 2, 3, 3, 3]2.Add an item to a set:
my_set = set(my_list)
my_set = {1, 2, 3}3.Remove an item from a set by its value:
my_set.add(4)
my_set = {1, 2, 3}4.Check if an item is in a set:
my_set.remove(3)
my_set = {1, 2, 3}5.Get the length of a set:
if 3 in my_set:
print("The item is in the set.")
my_set = {1, 2, 3}6.Loop through the items in a set:
set_length = len(my_set)
my_set = {1, 2, 3}7.Get the union of two sets:
for item in my_set:
print(item)
set1 = {1, 2, 3}8.Get the intersection of two sets:
set2 = {3, 4, 5}
union_set = set1.union(set2)
set1 = {1, 2, 3}Share and Support
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
@Python_Codes
BY Python Codes
Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283
Share with your friend now:
tg-me.com/python_codes/252