세트와 튜플

개발자를 위한 Python 입문

Jasmin Ludolf

Senior Data Science Content Developer

세트

  • 고유한 데이터 포함

  • 변경 불가

    • 값은 추가하거나 제거할 수 있지만, 변경할 수는 없음
  • 중복을 식별하고 제거하는 것이 이상적

  • (리스트와 같은 다른 데이터 구조에 비해) 빠른 검색

개발자를 위한 Python 입문

세트 만들기

  • 세트 = {}
  • : = 딕셔너리
  • : 없음 = 세트
# Create a set of ingredients
ingredients = {"pasta", "tomatoes", "pasta", 
                 "basil", "garlic", "olive oil", "salt"}
print(ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'}
개발자를 위한 Python 입문

세트로 변환하기

# Existing list variable
ingredients_list = ["pasta", "tomatoes", "garlic", "basil"
                    "olive oil", "pasta", "salt"]


# Convert to a set unique_ingredients = set(ingredients_list)
# Check the data type type(unique_ingredients)
set
개발자를 위한 Python 입문

세트로 변환하기

print(unique_ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil'}
개발자를 위한 Python 입문

세트의 한계

  • 인덱스가 없습니다
    • 중복은 허용되지 않습니다
    • []로 부분 집합할 수 없습니다
# Trying to subset a set
print(unique_ingredients[0])
TypeError: 'set' object is not subscriptable
개발자를 위한 Python 입문

세트 정렬

ingredients = {"pasta", "tomatoes", "garlic", 
                 "basil", "olive oil", "salt"}


# Sorting a set print(sorted(ingredients))
['basil', 'garlic', 'olive oil', 'pasta', 'salt', 'tomatoes']
  • sorted()는 리스트를 반환
개발자를 위한 Python 입문

튜플

  • 변경 불가 - 변경할 수 없음
    • 값 추가 안 함
    • 값 삭제 안 함
    • 값 수정 안 함
  • 정렬됨
    • 인덱스로 부분 집합 가능(예: [0]{{4}})
  • 위치 정보 또는 식별자에 유용함

노트북 위의 자물쇠

1 https://unsplash.com/@towfiqu999999
개발자를 위한 Python 입문

튜플 만들기

# Creating a tuple
serving_sizes = (1, 2, 4, 6, 8)


# Convert another data structure to a tuple ingredients_tuple = tuple(ingredients_list)
개발자를 위한 Python 입문

튜플에 접근하기

# A tuple
serving_sizes = (1, 2, 4, 6, 8)

# Access the second element
print(serving_size[1])
2
개발자를 위한 Python 입문

연습해 봅시다!

개발자를 위한 Python 입문

Preparing Video For Download...