Python set Function with Examples

In Python, a set is a fundamental class that is integrated into the language, and this function serves as the constructor for this class. It facilitates the creation of a new set utilizing the elements provided during the invocation. The function accepts an iterable as its parameter and produces a new set object. The syntax for the constructor is outlined below.

Python set Function Syntax

It has the following syntax:

Example

set([iterable])

Parameters

  • iterable: a set of elements that cannot be altered.
  • Return

It returns a new set.

Different Examples for Python set Function

Let’s examine a few instances of the set function to grasp its capabilities.

Python set Function Example 1

An illustrative example of generating a set from iterable elements.

Example

# Python set() function example

# Calling function

result = set() # empty set

result2 = set('12')

result3 = set('logicpractice')

# Displaying result

print(result)

print(result2)

print(result3)

Output:

Output

set()

{'1', '2'}

{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}

Python set Function Example 2

Let’s consider an example to illustrate how the Python set function operates.

Example

# Python set() function example

# Calling function

result = set(['12','13','15'])

result2 = set(('j','a','v','a','t','p','o','i','n','t'))

result3 = set({1:'One',2:'Two',3:'Three'})

# Displaying result

print(result)

print(result2)

print(result3)

Output:

Output

{'15', '13', '12'}

{'n', 'v', 'a', 'j', 'p', 't', 'o', 'i'}

{1, 2, 3}

Python set Function Example 3

In this section, we will generate a collection of filtered elements. The function geteven is designed to return only the even numbers.

Example

# Python set() function example

def geteven(data):

    if data%2 == 0:

        return data

evenval = filter(geteven,[2,5,6,9,8,4])

# Calling function

result = set(evenval)

# Displaying result

print(result)

Output:

Output

{8, 2, 4, 6}

Input Required

This code uses input(). Please provide values below: