In Python, a set is an unordered collection of unique elements. It is similar to a list or a tuple, but unlike those data types, a set does not allow duplicate values. Sets are implemented using a hash table, which allows for fast membership testing and set operations such as intersection and union.
To create a set in Python, you can use curly braces {} or the built-in
set() function. For example:
Sets are one of the 4 built-in data types in Python; it is an unordered collection data type that is iterable, mutable, and does not allow for duplicate elements.
Example:
set1 = {"Delhi","Kolkata","Mumbai"}
The advantage of using a set as opposed to a list is that it uses a hash table for performing set operations, which is more optimized.
Sets are unordered, as a result of which items cannot be accessed using indexes as in the case of lists. However, we can loop through the items using a loop.
Example:
set1 = {"Delhi","Kolkata","Mumbai"}
for x in set1:
print(x)
OUTPUT:
Delhi
Mumbai
Kolkata
We can add elements to a set as follows:
set1.add("Chennai")
To remove a specific element:
set1.remove("Delhi")
To clear all elements from the set:
set1.clear()
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In Python, a set is an unordered collection of unique elements. It is similar to a list or a tuple, but unlike those data types, a set does not allow duplicate values. Sets are implemented using a hash table, which allows for fast membership testing and set operations such as intersection and union.
To create a set in Python, you can use curly braces {} or the built-in set() function. For example:
Sets are one of the 4 built-in data types in Python; it is an unordered collection data type that is iterable, mutable, and does not allow for duplicate elements.
Example:
The advantage of using a set as opposed to a list is that it uses a hash table for performing set operations, which is more optimized.
Sets are unordered, as a result of which items cannot be accessed using indexes as in the case of lists. However, we can loop through the items using a loop.
Example:
We can add elements to a set as follows:
To remove a specific element:
To clear all elements from the set: