Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Sets | Data Structures
Introduction to Python with Cursor

bookSets

メニューを表示するにはスワイプしてください

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.
question mark

What is a key property of a Python set?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  4
some-alt