The Wayback Machine - https://web.archive.org/web/20241005044407/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.



Similar Reads

Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Zip function in Python to change to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co
2 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Matplotlib.axis.Axis.set() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.set() Function The Axis.set() function in axis module of matplotlib library is a property batch setter. Pass
2 min read
Matplotlib.axis.Tick.set() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Tick.set() Function The Tick.set() function in axis module of matplotlib library is a property batch setter. Pass
2 min read
Python Set discard() Function
Python discard() is a built-in method to remove elements from the set. The discard() method takes exactly one argument. This method does not return any value. Example: In this example, we are removing the integer 3 from the set with discard() in Python. C/C++ Code my_set = {1, 2, 3, 4, 5} my_set.discard(3) print(my_set) Output {1,2,4,5}Python Set d
3 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod
2 min read
ord() function in Python
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a U
3 min read
Print powers using Anonymous Function in Python
Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano
2 min read
Maximum length of consecutive 1's in a binary string in Python using Map function
We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a
1 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Prefix sum array in Python using accumulate function
We are given an array, find prefix sums of given array. Examples: Input : arr = [1, 2, 3] Output : sum = [1, 3, 6] Input : arr = [4, 6, 12] Output : sum = [4, 10, 22] A prefix sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence {a, b, c, ...} are a, a+b, a+b+c and so on. We can solve this problem
1 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec
2 min read
Union() function in Python
Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting uni
3 min read
Python | Permutation of a given string using inbuilt function
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA We have existing solution for this problem please refer Permutations of a given
2 min read
sciPy stats.tsem() function | Python
scipy.stats.tsem(array, limits=None, inclusive=(True, True)) calculates the trimmed standard error of the mean of array elements along the specified axis of the array. Its formula :- Parameters : array: Input array or object having the elements to calculate the trimmed standard error of the mean. axis: Axis along which the trimmed standard error of
2 min read
Python | fsum() function
fsum() is inbuilt function in Python, used to find sum between some range or an iterable. To use this function we need to import the math library. Syntax : maths.fsum( iterable ) Parameter : iterable : Here we pass some value which is iterable like arrays, list. Use : fsum() is used to find the sum of some range, array , list. Return Type : The fun
1 min read