Set is collection type in python like List but more restricted than list type. Such as,
1. Set is unordered Syntax to create a set:
# using curely brackets
set_name = {"First", "Second", "Third"}
# using set() constructor
set_name = set(("First", "Second", "Third"))
# Creating a set and print the elements
languages = {"Java", "Python", "C++"}
print(languages)
# Output:
{'C++', 'Python', 'Java'}
# A set elements can be different types
Here we create a set of string, int, boolean
demo_set = {"Java", 'Honda', 25, True, False}
print(demo_set)
# Output
{False, True, 25, 'Java', 'Honda'}
Note: In python, we can use double quotation " " or single quotation ' ' for string values. Both are same. But good practice is to use double quotation " " when you work on strings (sequence of characters)
Yes, you got the above result as set type is unordered.
# No duplicate elements allowed
Though you don't get any compile time error, hence the duplicate elements will be eliminated automatically by the compiler.
unique_names = {"Mark", "Helena", "Jenkov", "Mark"}
print(unique_names)
# Output:
{'Helena', 'Jenkov', 'Mark'}
Note: Boolean value like True is considered 1 and False is considered 0. So what output you will get from the below example?
demo_set = {"Java", 1, False, 0, True}
print(demo_set)
# Output:
{False, 1, 'Java'} # Possible to get different result in your compiler
# Using for loop
We can simply loop through or iterate set elements using for loop.
languages = {"Java", "Python", "C++", "Rust", "JavaScript"}
for x in languages:
print(x)
If you run the above python file, you will get the following output (not that it doesn't maintain insertion order)
Python
C++
Java
Rust
JavaScript