Python built-in Method - set()
The set()
function is a built-in Python method that is used to create a set data type. A set is an unordered collection of unique elements. The set()
function can be used to convert other data types, such as lists, tuples, and strings, into a set.
The syntax for the set()
function is as follows:
set(iterable)
iterable
: The iterable object to be converted into a set.
Here are some examples of how the set()
function can be used:
>>> s = set() >>> s.add(1) >>> s.add(2) >>> s.add(3) >>> print(s) {1, 2, 3}
In this example, we create an empty set s
using the set()
function. We then add the elements 1, 2, and 3 to the set using the add()
method. Finally, we print the set.
>>> lst = [1, 2, 3, 3, 2, 1] >>> s = set(lst) >>> print(s) {1, 2, 3}
In this example, we create a list lst
with duplicate elements. We then use the set()
function to convert the list into a set. The set contains only the unique elements from the list.
>>> s1 = set("hello") >>> s2 = set("world") >>> print(s1.union(s2)) {'l', 'h', 'o', 'w', 'e', 'd', 'r'}
In this example, we create two sets s1
and s2
from two different strings. We then use the union()
method to combine the two sets into a single set containing all the unique elements from both sets.
The set()
function is a useful built-in method in Python that provides a convenient way to create a set data type from other iterable objects. The set data type is useful for performing set operations, such as union, intersection, and difference, and for removing duplicate elements from a collection.