Set Basics

Creating and using sets

Interview Relevant: Unique collections

Set Basics

Sets are unordered collections of unique elements.

Code Examples

Basic set operations.

python
1# Create sets
2empty = set()  # NOT {} (that's a dict!)
3nums = {1, 2, 3, 4, 5}
4from_list = set([1, 2, 2, 3])  # {1, 2, 3}
5
6# Sets remove duplicates
7{1, 1, 2, 2, 3}  # {1, 2, 3}
8
9# Membership test O(1)
103 in nums  # True
11
12# Length
13len(nums)  # 5
14
15# Iterate (order not guaranteed)
16for n in nums:
17    print(n)
18
19# Sets are mutable
20nums.add(6)
21nums.remove(1)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In