搜尋此網誌

2026年5月12日星期二

Tuples and Sets in Python

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

Subscriptable means you can use square brackets [] to access elements by position (like lists, tuples, strings).

Sets are unordered collections → they don’t have positions or indices.

That’s why Python raises this 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']

mySet = {'a', 'b', 'c'}
mySet.discard('a') print(mySet)

mySet.remove('a') → removes 'a', but raises an error if 'a' is not found. mySet.discard('a') → removes 'a' if present, but does nothing if not found (safer).


def returnsMultipleValues(): return 1, 2, 3 print(type(returnsMultipleValues()))

return 1, 2, 3 → In Python, when you separate values with commas, they are automatically packed into a tuple.

Equivalent to: return (1, 2, 3)
So the function returns (1, 2, 3).
type(returnsMultipleValues()) → This checks the type of the returned object.

Output: <class 'tuple'>

a, b, c = returnsMultipleValues()

returnsMultipleValues() returns a tuple (1, 2, 3).

Python then unpacks that tuple into the three variables:
a = 1
b = 2
c = 3

Unpacking variables in Python means taking a collection (tuple, list, set, dict, etc.) and assigning its elements to multiple variables at once.

Microsoft Copilot

沒有留言:

發佈留言