In Python, sets and indexes are two different concepts, and they don’t work together the way lists or tuples do.
The error 'set' object is not subscriptable means you tried to access a set element by index, like this:
mySet = {'a', 'b', 'c'}
print(mySet[0]) # ❌ Error
Defined with curly braces {} or the set() constructor.
mySet = set(('a', 'b', 'c'))
('a', 'b', 'c') → This is a tuple containing three elements.
set(('a', 'b', 'c')) → The set() constructor takes that tuple and converts it into a set.
Result: {'a', 'b', 'c'}
Sets automatically remove duplicates (though here there aren’t any).
mySet now holds a set with the elements 'a', 'b', 'c'.
myList = ['a', 'b', 'b', 'c', 'c'] myList = list(set(myList)) print(myList)
['a', 'b', 'b', 'c', 'c'] → a list with duplicates.
set(myList) → converts the list into a set, automatically removing duplicate
list(set(myList)) → converts the set back into a list
Output: ['a', 'b', 'c']
But the order may vary, e.g. ['b', 'c', 'a'].
mySet.add('d') inserts the element 'd' into the set.
If 'd' was already inside, nothing changes (sets don’t allow duplicates).
while len(mySet):
print(mySet.pop())
Condition: while len(mySet):
The loop runs as long as the set is not empty (len(mySet) > 0).
Inside the loop:
mySet.pop() removes and returns an arbitrary element from the set.
print() displays that element.
Iteration:
Each loop removes one element until the set becomes empty.
Loop ends when len(mySet) == 0.
The order is not guaranteed because sets are unordered. Running the same code again may give a different sequence.
myList = ['a', 'b', 'c'] print(myList.pop()) # 'c' (last element) print(myList.pop(0)) # 'a' (index 0) print(myList) # ['b']
return 1, 2, 3 → In Python, when you separate values with commas, they are automatically packed into a tuple.return (1, 2, 3)(1, 2, 3).type(returnsMultipleValues()) → This checks the type of the returned object.<class 'tuple'>
a, b, c = returnsMultipleValues()
returnsMultipleValues() returns a tuple (1, 2, 3).
沒有留言:
發佈留言