Python set() Function – Tutorial with Examples

The set() function in Python is a built-in function that creates a set object. Sets are used to store multiple items in a single variable. Unlike lists or tuples, sets are unordered, unchangeable and do not allow duplicate values.

Syntax

set(iterable)

Parameters

  • iterable : An object that can be iterated (e.g. list, tuple, dictionary, string, set etc.). The iterable elements will be converted to a set.

Return Value

The set() function returns a set object, which is an unordered and unchangeable collection of unique elements.

Examples

Example 1: Creating a Set from a List

# Creating a set from a list
numbers = [1, 2, 3, 4, 5, 1, 2, 3]
unique_numbers = set(numbers)
print(unique_numbers)

Output

{1, 2, 3, 4, 5}

In this example, a list of numbers is created, and the set() function is used to convert the list into a set. The set will contain only the unique elements from the list, and any duplicates will be removed. The resulting set is then printed to the console.

Example 2: Creating a Set from a String

# Creating a set from a string
string = "hello world"
unique_chars = set(string)
print(unique_chars)

Output

{' ', 'o', 'd', 'l', 'e', 'r', 'w', 'h'}

In this example, a string is created, and the set() function is used to convert the string into a set. The set will contain only the unique characters from the string. The resulting set is then printed to the console.

Example 3: Creating a Set from a Tuple

# Creating a set from a tuple
numbers = (1, 2, 3, 4, 5, 1, 2, 3)
unique_numbers = set(numbers)
print(unique_numbers)

Output

{1, 2, 3, 4, 5}

In this example, a tuple of numbers is created, and the set() function is used to convert the tuple into a set. The set will contain only the unique elements from the tuple, and any duplicates will be removed. The resulting set is then printed to the console.

Use Cases

The set() function is used to create sets in Python, which can be used in a variety of ways. Some common use cases of the set() function are:

  • Removing duplicates from a collection of elements.
  • Performing mathematical set operations, such as union, intersection, and difference.
  • Checking for membership in a set, which is faster than checking for membership in a list or tuple.
  • Determining the common elements between two or more sets.
  • Working with sets in a functional programming style, where elements are transformed and filtered using set operations.

In conclusion, the set() function is a powerful tool in Python, and it is commonly used in a variety of applications that require working with collections of unique elements.

Leave a Reply

Your email address will not be published. Required fields are marked *