• Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Sets in Python

A Set in Python programming is an unordered collection data type that is iterable and has no duplicate elements. While sets are mutable, meaning you can add or remove elements after their creation, the individual elements within the set must be immutable and cannot be changed directly.

Set are represented by { } (values enclosed in curly braces)

The major advantage of using a set, as opposed to a list , is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table . Since sets are unordered, we cannot access items using indexes as we do in lists.

Example of Python Sets

Time Complexity: O(1) Auxiliary Space: O(1)

Type Casting with Python Set method

The Python set() method is used for type casting.

Python set is an unordered datatype, which means we cannot know in which order the elements of the set are stored.

Time Complexity: O(n) Auxiliary Space: O(n)

Check unique and  Immutable with Python Set

Python sets cannot have duplicate values. While you cannot modify the individual elements directly, you can still add or remove elements from the set.

The first code explains that the set cannot have a duplicate value. Every item in it is a unique value. 

The second code generates an error because we cannot assign or change a value once the set is created. We can only add or delete items in the set.

Heterogeneous Element with Python Set

Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string, integer, boolean, etc datatypes.

Python Frozen Sets

Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. It can be done with frozenset() method in Python.

While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. 

If no parameters are passed, it returns an empty frozenset.

Internal working of Set

This is based on a data structure known as a hash table.  If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List.

In, Python Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.

Set Implementation:

Sets in Python - Internal Working

Sets with Numerous operations on a single HashTable:

Sets in Python - Hash Table

Methods for Sets

Adding elements to python sets.

Insertion in the set is done through the set.add( ) function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case it can become O(n) .

Union operation on Python Sets

Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. The Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done.

Intersection operation on Python Sets

This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done.

Finding Differences of Sets in Python

To find differences between sets. Similar to finding differences in the linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1))

Clearing Python Sets

Set Clear() method empties the whole set inplace.

However, there are two major pitfalls in Python sets: 

  • The set doesn’t maintain elements in any particular order.
  • Only instances of immutable types can be added to a Python set.

Time complexity of Sets

OperationAverage caseWorst Casenotes
x in sO(1)O(n) 
Union s|tO(len(s)+len(t))  
Intersection s&tO(min(len(s), len(t))O(len(s) * len(t))replace “min” with “max” if t is not a set
Multiple intersection s1&s2&..&sn (n-1)*O(l) where l is max(len(s1),..,len(sn)) 
Difference s-tO(len(s))  

Operators for Sets

Sets and frozen sets support the following operators:

OperatorsNotes
key in scontainment check
key not in snon-containment check
s1 == s2s1 is equivalent to s2
s1 != s2s1 is not equivalent to s2
s1 <= s2s1 is subset of s2
s1 < s2s1 is proper subset of s2
s1 >= s2s1 is superset of s2
s1 > s2s1 is proper superset of s2
s1 | s2the union of s1 and s2
s1 & s2the intersection of s1 and s2
s1 – s2the set of elements in s1 but not s2
s1 ˆ s2the set of elements in precisely one of s1 or s2

Recent articles on Python Set.

Sets in Python – FAQs

What are sets in python.

Sets in Python are unordered collections of unique elements. They are defined using curly braces {} or the set() function and are useful for storing distinct items and performing mathematical set operations like union, intersection, and difference. # Creating a set my_set = {1, 2, 3, 4} print(my_set) # Output: {1, 2, 3, 4} # Using the set() function another_set = set([1, 2, 3, 4]) print(another_set) # Output: {1, 2, 3, 4}

How do you calculate sets in Python?

Sets in Python support various operations for calculating unions, intersections, differences, and symmetric differences. set1 = {1, 2, 3} set2 = {3, 4, 5} # Union print(set1 | set2) # Output: {1, 2, 3, 4, 5} # Intersection print(set1 & set2) # Output: {3} # Difference print(set1 - set2) # Output: {1, 2} # Symmetric Difference print(set1 ^ set2) # Output: {1, 2, 4, 5}

What is set and tuple in Python?

Set : An unordered collection of unique elements. Defined with curly braces {} or set() . Elements cannot be accessed by index. Tuple : An ordered collection of elements. Defined with parentheses () or tuple() . Elements can be accessed by index. Tuples are immutable.

Do sets exist in Python?

Yes, sets exist in Python and are part of the built-in data types provided by the language. They are commonly used for membership tests, removing duplicates from a sequence, and performing set operations. my_set = {1, 2, 3} print(2 in my_set) # Output: True

How to input set in Python?

To input a set in Python, you can use the input() function to get user input and then convert it into a set. For example, you can read a string of numbers separated by spaces and convert them to a set of integers. # Input a set from user input_str = input("Enter elements separated by space: ") input_list = input_str.split() # Split the input string into a list input_set = set(map(int, input_list)) # Convert list to set of integers print(input_set) # Output: Set of input elements This code snippet allows the user to input a set of numbers separated by spaces, which are then converted into a set of integers.

Similar Reads

Please login to comment....

  • PS5 Digital vs. Disc : Which PlayStation 5 Should You Buy in 2024?
  • AMD vs. Nvidia Graphics Cards 2024: Which GPU Should You Choose?
  • Top IPTV-Anbieter in Österreich für günstiges Streaming in 2024
  • IPTV Austria: Top 10 IPTV Subscription Providers for Austrian and International Channels
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

TypeError: NoneType object does not support item assignment

avatar

Last updated: Apr 8, 2024 Reading time · 3 min

banner

# TypeError: NoneType object does not support item assignment

The Python "TypeError: NoneType object does not support item assignment" occurs when we try to perform an item assignment on a None value.

To solve the error, figure out where the variable got assigned a None value and correct the assignment.

typeerror nonetype object does not support item assignment

Here is an example of how the error occurs.

We tried to assign a value to a variable that stores None .

# Checking if the variable doesn't store None

Use an if statement if you need to check if a variable doesn't store a None value before the assignment.

check if variable does not store none

The if block is only run if the variable doesn't store a None value, otherwise, the else block runs.

# Setting a fallback value if the variable stores None

Alternatively, you can set a fallback value if the variable stores None .

setting fallback value if the variable stores none

If the variable stores a None value, we set it to an empty dictionary.

# Track down where the variable got assigned a None value

You have to figure out where the variable got assigned a None value in your code and correct the assignment to a list or a dictionary.

The most common sources of None values are:

  • Having a function that doesn't return anything (returns None implicitly).
  • Explicitly setting a variable to None .
  • Assigning a variable to the result of calling a built-in function that doesn't return anything.
  • Having a function that only returns a value if a certain condition is met.

# Functions that don't return a value return None

Functions that don't explicitly return a value return None .

functions that dont return value return none

You can use the return statement to return a value from a function.

use return statement to return value

The function now returns a list, so we can safely change the value of a list element using square brackets.

# Many built-in functions return None

Note that there are many built-in functions (e.g. sort() ) that mutate the original object in place and return None .

The sort() method mutates the list in place and returns None , so we shouldn't store the result of calling it into a variable.

To solve the error, remove the assignment.

# A function that returns a value only if a condition is met

Another common cause of the error is having a function that returns a value only if a condition is met.

The if statement in the get_list function is only run if the passed-in argument has a length greater than 3 .

To solve the error, you either have to check if the function didn't return None or return a default value if the condition is not met.

Now the function is guaranteed to return a value regardless of whether the condition is met.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Return a default value if None in Python
  • Why does my function print None in Python [Solved]
  • Check if a Variable is or is not None in Python
  • Convert None to Empty string or an Integer in Python
  • How to Convert JSON NULL values to None using Python
  • Join multiple Strings with possibly None values in Python
  • Why does list.reverse() return None in Python

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

IMAGES

  1. Fix TypeError: 'str' object does not support item assignment in Python

    set' object does not support item assignment python

  2. Python TypeError: 'tuple' object does not support item assignment

    set' object does not support item assignment python

  3. Python typeerror tuple object does not support item assignment

    set' object does not support item assignment python

  4. How to fix typeerror: 'range' object does not support item assignment

    set' object does not support item assignment python

  5. Fix TypeError: 'str' object does not support item assignment in Python

    set' object does not support item assignment python

  6. Python TypeError: 'tuple' object does not support item assignment Solution

    set' object does not support item assignment python

VIDEO

  1. COM Object Create Item Python Issue resolved

  2. Python for Data Science NPTEL Assignment 3 week 3 answers 2024

  3. Sets in Python

  4. Python Set Object Is Not Subscriptable

  5. The work done on an object does not depend on the:

  6. Python :'str' object does not support item assignment(5solution)