Python set() Built in Function

A set in Python is an unordered collection of unique items that supports various operations such as membership testing, union, intersection, difference and symmetric difference. The syntax for creating a set is:

set(iterable)

where iterable is any object that can be iterated over, such as a list, a tuple or a string. Alternatively, you can use curly braces {} to create a set with literal values.

Here are some examples of creating sets with different iterables:


# Create a set from a list
my_set = set([1, 2, 3])
print(my_set)
# Output: {1, 2, 3}

# Create a set from a tuple
my_set = set((4, 5, 6))
print(my_set)
# Output: {4, 5, 6}

# Create a set from a string
my_set = set("hello")
print(my_set)
# Output: {'h', 'e', 'l', 'o'}

# Create a set with literal values
my_set = {7, 8 ,9}
print(my_set)
# Output: {7 ,8 ,9}

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions