Sets
メニューを表示するにはスワイプしてください
A set is a collection of unique, unordered values. It doesn't allow duplicates and doesn't keep order.
Sets are useful for removing repeats, checking membership, or comparing groups with operations like union and intersection.
Creating a Set
Create a set with curly braces, without key-value pairs:
fruits = {'apple', 'banana', 'cherry'}
Or use set() to convert another collection, like a list, which also removes duplicates automatically.
Key Properties of Sets
- Unordered: elements have no fixed order;
- No duplicates: repeated items are ignored;
- Mutable: you can add or remove items;
- Immutable items only: allowed types include numbers, strings, tuples;
- No indexing: elements can't be accessed by position.
Sets are optimized for fast membership tests with the in keyword.
Adding and Removing Items
.add(): to insert a new item into a set;.remove(): to remove an item, it raises an error if the item doesn't exist;.discard(): also removes item, but quietly skips if the item's not found.
Set Operations
Python sets support:
- Union (
|or.union()): combine elements from both sets; - Intersection (
&or.intersection()): keep only common elements; - Difference (
-or.difference()): elements in one set but not the other.
These operations are handy for comparing roles, flags, or datasets.
Summary
- Sets are unordered collections of unique values;
- They automatically remove duplicates;
- You can add or remove items, but can't access by position;
- Use sets for fast comparisons, membership checks, and when you don't care about order.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 4