![]() |
|
[Tut] Python TypeError ‘set’ object is not subscriptable - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python TypeError ‘set’ object is not subscriptable (/thread-99934.html) |
[Tut] Python TypeError ‘set’ object is not subscriptable - xSicKxBot - 09-11-2022 Python TypeError ‘set’ object is not subscriptable 5/5 – (1 vote) ![]() Minimal Error Example Given the following minimal example where you create a set and attempt to access an element of this set using indexing or slicing: Code: my_set = {1, 2, 3}
my_set[0]If you run this code snippet, Python raises the Code: TypeError: 'set' object is not subscriptableCode: Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> my_set[0]
TypeError: 'set' object is not subscriptableThe Python Code: TypeError: 'set' object is not subscriptableHowever, sets are unordered collections of unique elements: they have no ordering of elements. Thus, you cannot use slicing or indexing, operations that are only possible on an ordered type. Recommended Tutorial: The Ultimate Guide to Python SetsHow to Fix the Error? How to fix the Code: TypeError: 'set' object is not subscriptableTo fix the Code: TypeError: 'set' object is not subscriptableHere’s an example where you convert the unordered set to an ordered list first. Only then you use indexing or slicing so the error doesn’t occur anymore: Code: my_set = {1, 2, 3} # Convert set to list:
my_list = list(my_set) # Indexing:
print(my_list[0])
# 1 # Slicing:
print(my_list[:-1])
# [1, 2]Alternatively, you can also convert the set to a tuple to avoid the Code: TypeError: 'set' object is not subscriptableCode: my_tuple = tuple(my_set)Let’s end this article with a bit of humor, shall we? ![]() Programmer Humor There are only 10 kinds of people in this world: those who know binary and those who don’t. ![]() ![]() ~~~ There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary. ![]() ![]()
|