Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is iterable, mutable and has no duplicate elements.
-dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object
-add() method adds a given element to a set if the element is not present in the set.
-remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
-discard() method removes the specified item from the set. This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
Code:
example=set()
print(dir(example))
print("\n the set is to hold anything")
example.add(42)
example.add(False)
example.add(3.14159)
example.add("Thorium")
print(example)
print("\n A set, the order does not matter. it may appear in different ways.")
print("Sets will not contain duplicates")
print("If I add 42 the set will not change.")
print(" \n Make a simple removal. If the element is not there it will throw an error.")
example.remove(42)
print(example)
example.discard(50)
print(" \n Second way to create and repopulate a set.")
example2=set([28,True,2.17,'Carbon'])
print(example2)
print(len(example2))
print("\n You can create a union and combine the sets.")
odds= set([1,3,5,7,9])
evens=set([2,4,6,8,10])
primes=set([2,3,5,7])
composites=set([4,6,8,9,10])
print(' odds= ',odds)
print(" evens= ", evens)
print('\t odds.union(evens)=' ,odds.union(evens))
print("\n odds= ", odds)
print("\n primes= ", primes)
print(" \t odds.intersection(primes)= ", odds.intersection(primes))
print("\n See if the elements exists in a set.")
print("\n 2 in prime \t", 2 in primes)
print("\n 9 in evens\t", 9 in evens)
Auf dieser Seite können Sie das Online-Video 16. Set in Python || Union and Intersection Method Python Programming || add(), remove(), discard() mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Bhavatavi 24 Juni 2022 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 4 Mal angesehen und es wurde von 0 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!