Python Sets
In Python, a Set is an unordered collection of unique elements, that means duplicate elements are not allowed in a Set. Set is one of the 4 built-in data types in Python, the other 3 are List, Tuple and Dictionary.
Sets in Python are created by placing all the elements inside curly braces {...}
, separated by commas. A Set can include items of different data types, like Integers, Float, Strings.
Here is how you can create a Set, in Python.
Example
my_set = {"apple", 5, 3.14, True} print(my_set) #Outputs: {True, 3.14, 5, 'apple'}
Get Length of a Set
In order to calculate how many items are present in a set, we can use the len()
function. Here is an example:
Example
my_set = {"apple", "orange", "mango", "grapes"} print(len(my_set)) #Outputs: 4 set2 = {"a", 2, 6.14, True, "grapes"} print(len(set2)) #Outputs: 5
Duplicate items in a Set
We already discussed duplicate items are not allowed in a Set. Now let’s see what happen if we add duplicate items in a set.
Example
my_set = {"apple", "banana", "mango", "apple"} print (my_set) #Outputs: {'apple', 'mango', 'banana'}
As you can see that, when we run this code it prints duplicate item only once.
Also remember that 1 and True are same.
Example
my_set = {"apple", "banana", "watermelon", "apple", True, 1} print (my_set) #Outputs: {True, 'watermelon', 'banana', 'apple'}
Python Sets – Add items
Python Sets are mutable, which means we can modify them by adding or removing items. We cannot directly modify individual items within a set, we need to remove the item that we want to modify and add the modified item back to the set. Here is an example:
Example
my_set = {"apple", "banana", "cherry"} # Remove item you want to modify my_set.remove("banana") # Add the modified item back to the set my_set.add("mango") print(my_set) # Outputs: {"apple", "cherry", "banana"}
Access Set Items
We cannot access set items by referring to an index, like we did in Lists and tuples. Infact we have to iterate over a Set or by using specific methods to access Set items. Here is an example:
Example
my_set = {"apple", "banana", "cherry"} for item in my_set: print(item) """Outputs: apple banana cherry """
Check if an item is Present in a Set
To check if any specific item is present in a set or not we can use the in operator. It returns True if an item is present in a Set, otherwise False. Here is an example:
Example
my_set = {"apple", "banana", "cherry"} print ("banana" in set) #Outputs: True print ("mango" in set) #Outputs: False
Share This Post!