The Wayback Machine - https://web.archive.org/web/20241216145206/https://www.geeksforgeeks.org/python-set-function/
Open In App

Python | set() Function

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

set() method is used to convert any of the iterable to a sequence of iterable elements with distinct elements, commonly called Set. In Python, the set() function is a built-in constructor that is used to initialize a set or create an empty. In this article, we will see about set() in Python and how we can convert an iterable to a sequence with unique elements in Python.

Python set() Method Syntax

Syntax: set(iterable)
Parameters : Any iterable sequence like list, tuple or dictionary.
Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument. 

What is Python set() Function?

Set, a term in mathematics for a sequence consisting of distinct languages is also extended in its language by Python and can easily be made using set(). set() method is used to convert an iterable to a sequence with unique elements in Python, commonly called Set. It is a built-in constructor function that is used to create an empty set or initialize a set with elements.

Properties of Python set() Method

  • No parameters are passed to create the empty set
  • The dictionary can also be created using a set, but only keys remain after conversion, and values are lost.

set() Function in Python Examples

Below are the ways by which we can use set() in Python:

  • Creating an Empty Set
  • Using set() with List
  • Using set() with Tuples
  • Creating set with Range
  • Converting Dictionary into a Set

Creating a Set by using set() Function

In this example, we are creating a Set using set() function.

Python
# we are creating an 
#empty set by using set()

s = set()
print("Type of s is ",type(s))

Output
Type of s is  <class 'set'>

set() Function with List

In this example, we are using set() with List. Here, we will convert an iterable to a sequence with unique elements in Python.

Python
# working of set() on list
# initializing list 
lis1 = [ 3, 4, 1, 4, 5 ]

# Printing iterables before conversion
print("The list before conversion is : " + str(lis1))

# Iterables after conversion are 
# notice distinct and elements
print("The list after conversion is : " + str(set(lis1)))

Output
The list before conversion is : [3, 4, 1, 4, 5]
The list after conversion is : {1, 3, 4, 5}

set() Function with Tuple

In this example, we are using set() function with tuple.

Python
# working of set() on tuple
# initializing tuple
tup1 = (3, 4, 1, 4, 5)

# Printing iterables before conversion
print("The tuple before conversion is : " + str(tup1))

# Iterables after conversion are 
# notice distinct and elements
print("The tuple after conversion is : " + str(set(tup1)))

Output
The tuple before conversion is : (3, 4, 1, 4, 5)
The tuple after conversion is : {1, 3, 4, 5}

set() Function with Range

In this example, we are using set() function with range function. Here, we will convert an iterable to a sequence with unique elements in Python.

Python
# working of set() on range

# initializing range 
r = range(5)

r=set(r)
# Iterables after conversion are 
# notice distinct and elements
print("The Range after conversion is : " + str(r))

Output
The Range after conversion is : {0, 1, 2, 3, 4}

Demonstration of set() Method with Dictionary

In this example, we are seeing the demonstration of set() with Dictionary and it’s working.  

Python
# Python3 code to demonstrate the 
# working of set() on dictionary

# initializing list 
dic1 = { 4 : 'geeks', 1 : 'for', 3 : 'geeks' } 

# Printing dictionary before conversion
# internally sorted
print("Dictionary before conversion is : " + str(dic1))

# Dictionary after conversion are 
# notice lost keys
print("Dictionary after conversion is : " + str(set(dic1)))

Output
Dictionary before conversion is : {4: 'geeks', 1: 'for', 3: 'geeks'}
Dictionary after conversion is : {1, 3, 4}

Python | set() Function – FAQs

What does function() Do in Python?

The term function() doesn’t specifically refer to any built-in Python function. If you’re referring to how functions are generally used in Python, a function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You define functions using the def keyword.

What is all() in Python?

The all() function in Python checks if all elements in an iterable are true. It returns True if all elements are truthy (or if the iterable is empty), and False otherwise. An element is considered “truthy” if it evaluates to True in a Boolean context, which means non-zero numbers, non-empty strings, and collections with at least one item, among others, are truthy.

Example of all():

print(all([1, 2, 3]))  # True because all are non-zero
print(all([0, 1, 2])) # False because 0 is falsy
print(all([])) # True, because the iterable is empty

What Does __function Mean in Python?

In Python, the double underscore prefix __ before a function name (like __function) is a naming convention indicating a private method. It is used to suggest that the method should not be accessed from outside the class, a convention that Python enforces by name mangling: the interpreter changes the name of the method in a way that makes it harder to create subclass methods that accidentally override the private methods in the superclass.

How to Use any() and all()?

any() and all() are built-in Python functions that check the truthiness across an iterable.

  • any() returns True if at least one of the elements in the iterable is truthy. It is useful when you want to check if any items meet a particular condition.
  • all() returns True only if all elements in the iterable are truthy. It’s used when you need to ensure every item meets a certain condition.

Example of any() and all():

nums = [0, 1, 2, 3]

# Check if any number is even
print(any(n % 2 == 0 for n in nums)) # True, because 0 and 2 are even

# Check if all numbers are even
print(all(n % 2 == 0 for n in nums)) # False, because 1 and 3 are not even

What is mean() in Python?

mean() is a function typically used to calculate the average of numbers. While not a built-in Python function, mean() is available in libraries such as statistics (for basic statistical operations) and numpy (for numerical operations).

Example using statistics.mean():

import statistics

data = [1, 2, 3, 4, 5]
print(statistics.mean(data)) # Output: 3

This function is commonly used in data analysis and scientific computing to get the central tendency of data.



Next Article

Similar Reads

three90RightbarBannerImg