Python set Function with Examples - Python Tutorial | Logic Practice
Python Course / Other / Python set Function with Examples

Python set Function with Examples

BLUF: This lesson on Python set Function with Examples provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python set Function with Examples

Mastering Python set Function with Examples is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience