As per the Python’s Official Documentation, set
data structure is referred as Unordered Collections of Unique Elements
and that doesn’t support operations like indexing or slicing etc.
Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
When you define temp_set = {1, 2, 3}
it just implies that temp_set
contains 3 elements but there’s no index that can be obtained
>>> temp_set = {1,2,3}
>>> 1 in temp_set
>>> True
>>> temp_set[0]
>>> Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-10-50885e8b29cf>", line 1, in <module>
temp_set[0]
TypeError: 'set' object is not subscriptable
In Python, you cannot access values inside a set using indexing syntax. A set is an unordered collection of unique elements. Because a set is unordered, they do not record element position or insertion order. Therefore sets do not support indexing, slicing or other sequence-like behaviour.
Indexing syntax is suitable for iterable objects such as strings or lists.
If you attempt to index or slice a set, you will raise the “TypeError: ‘set’ object is not subscriptable”.
You can convert the set to a list using the built-in list() method to solve this error.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
- TypeError: ‘set’ object is not subscriptable
- Example: Trying to Index a Set Instead of a List
- Solution
- Example: Indexing a Set Instead of a Dictionary
- Solution
- Summary
TypeError: ‘set’ object is not subscriptable
Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part set object
tells us the error concerns an illegal operation for floating-point numbers.
The part “is not subscriptable” tells us we cannot access an element of the object in question.
Subscriptable objects contain a collection of objects, and we access these objects by indexing.
You cannot retrieve a specific value from a set using indexing. A Python set is an unordered collection of unique elements, therefore, does not maintain element position or order of insertion.
Example: Trying to Index a Set Instead of a List
Let’s look at an example where we have a set of integers; we want to get the last element of the set using the indexing operator. The code is as follows:
numbers = {2, 4, 6, 7, 8} print(f'The last number in the set is: {numbers[-1]}')
The index value -1 gets the last element in a collection.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-3a97ae86710b> in <module> 1 numbers = {2, 4, 6, 7, 8} 2 ----> 3 print(f'The last number in the set is: {numbers[-1]}') TypeError: 'set' object is not subscriptable
We get the TypeError because we are trying to access the elements of a set using indexing. Set objects do not support indexing, slicing or any other sequence-like behaviour.
Solution
To solve this error, we can convert the list to a set using the built-in list()
function and then access the list’s last element using indexing.
# Define set numbers = {2, 4, 6, 7, 8} # Convert set to list numbers_list = list(numbers) # Converted list print(numbers_list) # Confirming type is list print(type(numbers_list)) # Last element in list print(f'The last number in the list is: {numbers_list[-1]}')
Let’s run the code to get the result:
[2, 4, 6, 7, 8] <class 'list'> The last number in the list is: 8
Example: Indexing a Set Instead of a Dictionary
Another common source of this error is incorrectly creating a set instead of a dictionary then trying to access the set using indexing. Let’s look at an example.
We will write a program that allows users to buy items from a shop for a fantasy quest. First, we will define the shop, which will store the item names and prices:
shop = {"sword",25, "shield", 10, "armor", 40, "helmet", 20, "amulet", 50}
Then, we will define a variable called inventory
and assign an empty list to it. This list will store the items the user buys from the shop. We will also define a variable called gold
and assign an integer value of 100
to it. This value is the amount the user has to spend in the shop.
inventory = [] gold = 100
Next, we will define a function that takes the item the user wants to buy and the amount of gold the user has as parameters. If the amount of gold is greater or equal to the item’s price, we append the item to the inventory and then deduct the cost from the starting amount of gold. If the amount of gold is less than the item’s price, we will print that the user does not have enough gold to buy the item.
def buy(item, gold): if gold >= shop[item]: print(f'You have bought: {item}') inventory.append(item) gold -= shop[item] print(f'You have {gold} gold remaining') else: print(f'Sorry you do need {shop[item]} gold to buy: {item}')
Now we have the program, and we can ask the user what item they want to buy using the input()
function and then call the buy()
function.
item = input("What item would you like to buy for your quest?: ") buy(item, gold)
Let’s run the code to see what happens:
What item would you like to buy for your quest?: sword --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-644e6440f655> in <module> 15 item = input("What item would you like to buy for your quest?: ") 16 ---> 17 buy(item, gold) <ipython-input-6-644e6440f655> in buy(item, gold) 6 7 def buy(item, gold): ----> 8 if gold >= shop[item]: 9 print(f'You have bought: {item}') 10 inventory.append(item) TypeError: 'set' object is not subscriptable
We get the TypeError because the shop variable is a set, not a dictionary. We define a dictionary with key-value pairs with a colon between the key and the value of each pair. We use commas to separate key-value pairs, not keys from values. When we try to get the cost of an item using indexing, we are trying to index a set, and sets do not support indexing.
Solution
We need to define a dictionary using colons to solve this error. Let’s look at the revised code:
shop = {"sword":25, "shield":10, "armor":40, "helmet":20, "amulet":50} inventory = [] gold = 100 def buy(item, gold): if gold >= shop[item]: print(f'You have bought: {item}') inventory.append(item) gold -= shop[item] print(f'You have {gold} gold remaining') else: print(f'Sorry you do need {shop[item]} gold to buy: {item}') item = input("What item would you like to buy for your quest?: ") buy(item, gold)
Let’s run the code to get the result:
What item would you like to buy for your quest?: sword You have bought: sword You have 75 gold remaining
We successfully bought a sword for our fantasy quest and have 75 gold remaining.
Summary
Congratulations on reading to the end of this tutorial! The TypeError: ‘set’ object is not subscriptable occurs when you try to access elements of a set using indexing or slicing. You may encounter this when you incorrectly define a set instead of a dictionary. To create a dictionary, ensure you put a colon between the key and value in each pair and separate each pair with a comma.
If you want to access an element of a set using indexing, convert the set to a list using the list()
method.
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Set is a data structure that allows you to store multiple items in it. All the items inside it are unordered. It means the position or index for the elements of the set is random. If you are getting the error like ‘set’ object is not subscriptable in Python then this post is for you. In this entire tutorial, you will understand why this error comes and how you can solve this issue.
Before going to the solution to the problem let’s create a sample set for the problem. In python, you can create a set using the curly brackets( {}). Each element in the set is immutable. Let’s create it.
my_set ={10,20,30,40,50}
print(my_set)
Output
{40, 10, 50, 20, 30}
The root cause of the ‘set’ object is not subscriptable in python
The main and root cause for the TypeError: ‘set’ object is not subscriptable is that you are accessing the elements of the set using the index. Please note that when you create a set the elements are randomly located. Thus when you want to get the location of the element using the index, it throws an error.
For example, I want to get the second element of the set. And when I want to access the my_set(1), I will get the ‘set’ object is not subscriptable python error.
my_set ={10,20,30,40,50}
print(my_set[1])
Output
Solution for the ‘set’ object is not subscriptable error
The solution for this typerror is very simple. As the elements inside the set are randomly located. And if you want to access the elements through the index then you have to first convert the set to a list using the list() method. After that, you can easily locate the element using the index of the element.
Execute the below lines of code to get the elements of the set.
my_set ={10,20,30,40,50}
my_list = list(my_set)
print(my_list[1])
Output
Conclusion
Set is an immutable data structure. It is very useful when you don’t want to change the elements of it. If you want to get the element from the set using index then you have to first convert the set into the list. Otherwise, you will get the TypeError: ‘set’ object is not subscriptable error. The above method will solve your error if you are getting it.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.
Python shows TypeError: 'set' object is not subscriptable
error when you use the square brackets []
notation to access elements of a set object.
To fix this error, you’ll need to convert the set object to a list or a tuple first.
In Python, sets are unordered collections of unique elements. They are defined using curly braces {}
or the set()
constructor.
A set is not a subscriptable object, so when you try to access its element like this:
s = {1, 2, 3}
print(s[0]) # ❌
Python responds with TypeError: 'set' object is not subscriptable
:
Traceback (most recent call last):
File ...
my_set[0]
TypeError: 'set' object is not subscriptable
Python sets are not subscriptable, meaning they do not support access to elements using square brackets (the subscript notation).
When you need to access an element of a set using an index, you’ll need to convert it to a list or a tuple first as follows:
s = {1, 2, 3}
# Convert a Python set to a list
my_list = list(s)
print(my_list[0]) # 1 ✅
# Convert a Python set to a tuple
my_tuple = tuple(s)
print(my_tuple[0]) # 1 ✅
If you have no code that requires a set and you have access to the code (not imported from a module) then you can declare the variable as a list directly.
Use square brackets to declare a list as shown below:
s = [1, 2, 3] # This is a list
print(s[0]) # 1 ✅
It is important to be aware of the differences between sets and other collection types like lists and tuples so that you use the appropriate methods for working with sets in your code.
Conclusion
The Python TypeError: 'set' object is not subscriptable
error occurs when you attempt to access elements of a set using square brackets.
The error can be fixed by converting the set to a list or tuple first, then access the specific element using square brackets.
Alternatively, you can declare the set as a list if you don’t require a set and you have access to the code.
In this post, we will learn how to fix TypeError:object is not subscriptable error in Python. The TypeError is raised when trying to use an illegal operation on non subscriptable objects(set,int,float) or does not have this functionally. Python throws the TypeError object is not subscriptable if We use indexing with the square bracket notation on an object that is not indexable.
1.TypeError:object is not subscriptable Python
In this Python program example, accessing the integer variable values, accessing with the square bracket notation and since is not indexable.
number = 56789 print( number[0])
Output
print( number[0]) TypeError: 'int' object is not subscriptable
Solution TypeError:object is not subscriptable Python
We have to access the integer variable without index notation.Let us understand with the below example
number = 56789
print( ‘The value is :’,number)
Output
- TypeError:NoneType object is not subscriptable
- ValueError:Cannot convert non-finite values (NA or inf) to integer
- Fix ValueError: could not convert string to float
- Fixed Typeerror: nonetype object is not iterable Python
- ValueError:Cannot convert non-finite values (NA or inf) to integer
2.TypeError:object is not subscriptable set
We can’t access the set element by using the index notation.Running the below code will throw TypeError.To solve this error We have to use for loop to iterate over the set and display a single value.The Python object strings, lists, tuples, and dictionaries are subscribable their elements can be accessed using the index notation.
mySet = {3,6,9,12,15,18,121} print(mySet[0])
Output
print(mySet[0]) TypeError: 'set' object is not subscriptable
Solution object is not subscriptable set
In this example we have for loop to iterate over the set and display each element in the set.
mySet = {3,6,9,12,15}
for inx in mySet:
print(inx,end=”,”)
Output
3.TypeError:object is not subscriptable Pandas
In this example, we are finding the sum of Pandas dataframe column “Marks” that has int type. While applying the Lambda function on the ‘Marks’ column using index notation or subscript operator and encountering with TypeError: ‘int’ object is not subscriptable in Pandas.
import pandas as pd data = { 'Name': ['Jack', 'Jack', 'Max', 'David'], 'Marks':[97,97,100,100], 'Subject': ['Math', 'Math', 'Math', 'Phy'] } dfobj = pd.DataFrame(data) print(dfobj.dtypes) MarksGross = lambda x: int(x[1]) dfobj.Marks = dfobj.Marks.apply(MarksGross) Print(dfobj.Marks.sum())
Output
MarksGross = lambda x: int(x[1]) TypeError: 'int' object is not subscriptable
4. How to fix TypeError: int object is not Subscriptable Pandas
To solve Type Error with Pandas dataframe, We have not applied the lambda function using index notation instead use int(x) pass value of x inside () brackets.
import pandas as pd data = { 'Name': ['Jack', 'Jack', 'Max', 'David'], 'Marks':[97,97,100,100], 'Subject': ['Math', 'Math', 'Math', 'Phy'] } dfobj = pd.DataFrame(data) print(dfobj.dtypes) MarksGross = lambda x: int(x) dfobj.Marks = dfobj.Marks.apply(MarksGross) print(dfobj.Marks.sum())
Output
Name object Marks int64 Subject object dtype: object 394