# set 요소 추가, 삭제
nums1 = set()
nums2 = set()
nums1.add(1)
nums2.add(2)
nums1.update(nums2)
nums1.update([3])
nums1.update({4})
nums1.update('4')
print(nums1)
nums1.remove('4')
print(nums1)
# 결과
{1, 2, 3, 4, '4'}
{1, 2, 3, 4}
# set - operators
a, b = set(), set()
a = {1, 2}
b = {1, 3}
print(a - b)
print(a.difference(b))
print(a ^ b)
print(a.symmetric_difference(b))
print(a & b)
print(a.intersection(b))
x, y = set(), set()
x = {'aa', 'bb'}
y = {'aa', 'cc'}
print(x.difference('bb'))
print(x.difference({'bb'}))
# 결과
{2}
{2}
{2, 3}
{2, 3}
{1}
{1}
{'aa', 'bb'}
{'aa'}
# A set is a data type that consists of a collection of items
# much like a list.
# However, sets differ from lists in two important ways.
# The first is that they cannot have duplicate values in them,
# and the second is that the items they contain are unordered,
# like the key value pairs of a dictionary.
# Unlike lists or tuples sets cannot have their items accessed
# from them by index.
# So if you want to access the elements from a set,
# you can use a for loop.
# Sets are useful in situation where you want to use a collection
# of items, but you don't want duplicate items in the collection.
duplicate_nums = [1, 2, 3, 4, 1, 2, 3, 4, 5, 7, 10, 12, 10]
print(set(duplicate_nums))
print(f'length of duplicate_nums: {len(duplicate_nums)}')
print(list(set(duplicate_nums)))
print(f'length of unique nums: {len(list(set(duplicate_nums)))}')
# 결과
{1, 2, 3, 4, 5, 7, 10, 12}
length of duplicate_nums: 13
[1, 2, 3, 4, 5, 7, 10, 12]
length of unique nums: 8
# set의 복사
mountains = {'Everest', 'Kilimanjaro', 'Baekdoo'}
mountains2 = mountains.copy()
print(f'mountains is equal to mountains2? {mountains2 is mountains}')
# 결과
mountains is equal to mountains2? False
# set comprehensions
set_evens = {e for e in range(1, 10) if e % 2 == 0}
print(sorted(set_evens))
set_unique_letter = {l.lower() for l in 'ALLCAPS'}
print(sorted(set_unique_letter))
# 결과
[2, 4, 6, 8]
['a', 'c', 'l', 'p', 's']
댓글 영역