# Set 集合

當您想要儲存一堆元素，並確定這些元素只出現一次時，就會使用集合(set)。集合(set)的元素也必須是不可變的。您可以將其視為字典 (dictionary) 中沒有關聯值 (value) 的鍵 (key)

- 符號用大括號
- 內容必須是唯一值，不可重複；如果提供的元素有重複值，程式不會發生錯誤，set 只會存在一個元素
- 建立空白 set 要用函式 `set()`
- 資料不是序列，元素之間沒有索引及順序關係

```python
A = {"jlanksy", "drosas", "nmason"}

# Create an empty set
B = set()

# set 不會有重複的元素
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)                      # show that duplicates have been removed
# Output: {'orange', 'banana', 'pear', 'apple'}
```

#### Methods

##### .add()

`.add()` 新增元素

```python
s = {1, 2, 3, 4, 5}
s.add(6)
s.add(7)
s.add(7)

print(s)
# Output {1, 2, 3, 4, 5, 6, 7}
```

##### .remove()

`.remove()` 刪除元素

```python
s = {1, 2, 3, 4, 5}
s.remove(5)
#s.remove(6) # Error

print(s)
# Output {1, 2, 3, 4}
```

#### 範例

##### 元素 in set

```python
fruits = {'apple','banana','orange','lemon'}
print('tomato' in fruits)    # Output False
result = 'apple' in fruits
print(result)                # Output True
```

##### Set 交集

```python
fruits1 = {'apple','banana','orange','lemon'}
fruits2 = {'tomato','apple','banana'}
print(fruits1 & fruits2)   # Output {'apple', 'banana'}
print(fruits2 & fruits1)   # Output {'apple', 'banana'}
```

```python
nums1 = {1,2,3,4,5}
nums2 = {2,4,6,8,10}
print(nums1.intersection(nums2))  # Output {2, 4}
print(nums2.intersection(nums1))  # Output {2, 4}
```

##### Set 聯集

```python
fruits1 = {'apple','banana','orange','lemon'}
fruits2 = {'tomato','apple','banana'}
print(fruits1 | fruits2)  # Output {'orange', 'banana', 'tomato', 'lemon', 'apple'}
print(fruits2 | fruits1)  # Output {'orange', 'banana', 'tomato', 'lemon', 'apple'}
```

```python
nums1 = {1,2,3,4,5}
nums2 = {2,4,6,8,10}
print(nums1.union(nums2))  # Output {1, 2, 3, 4, 5, 6, 8, 10}
print(nums2.union(nums1))  # Output {1, 2, 3, 4, 5, 6, 8, 10}
```

##### Set 差集

```python
fruits1 = {'apple','banana','orange','lemon'}
fruits2 = {'orange','lemon','tomato'}
print(fruits1 - fruits2)  # Output {'apple', 'banana'}
print(fruits2 - fruits1)  # Output {'tomato'}
```

```python
nums1 = {1,2,3,4,5}
nums2 = {4,5,6,7,8}
print(nums1.difference(nums2))  # Output {1, 2, 3}
print(nums2.difference(nums1))  # Output {8, 6, 7}
```

##### Set 對稱差集

```python
fruits1 = {'apple','banana','orange','lemon'}
fruits2 = {'orange','lemon','tomato'}
print(fruits1 ^ fruits2)  # Output {'tomato', 'banana', 'apple'}
print(fruits2 ^ fruits1)  # Output {'tomato', 'banana', 'apple'}
```

```python
nums1 = {1,2,3,4,5}
nums2 = {4,5,6,7,8}
print(nums1.symmetric_difference(nums2)) # Output {1, 2, 3, 6, 7, 8}
print(nums2.symmetric_difference(nums1)) # Output {1, 2, 3, 6, 7, 8}
```