[2026] Python Data Types | Lists, Dictionaries, Tuples, and Sets — Complete Guide

[2026] Python Data Types | Lists, Dictionaries, Tuples, and Sets — Complete Guide

이 글의 핵심

Master Python built-in types: list, dict, tuple, set. Slicing, comprehensions, copying, defaultdict, and performance tips for beginners.

Introduction

Python’s built-in types are powerful and easy to use. This guide covers lists, dictionaries, tuples, and sets in depth. For the abstract data structures behind interviews, see arrays and lists, hash tables, and C++ map vs unordered_map.

1. List

What is a list?

A list is ordered and mutable. Elements can be of mixed types. Properties:

  • Order preserved (index access)
  • Duplicates allowed
  • Mutable (add, remove, change)
  • Mixed types allowed

Creating and indexing

다음은 python를 활용한 상세한 구현 코드입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, [1, 2]]
empty1 = []
empty2 = list()
nums = list(range(10))
print(nums)
print(fruits[0])
print(fruits[-1])
print(fruits[-2])
# print(fruits[10])  # IndexError
print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])
print(numbers[::2])
print(numbers[::-1])
sub = numbers[1:3]
sub[0] = 100
print(numbers)
print(sub)

List methods

다음은 python를 활용한 상세한 구현 코드입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

fruits = ["apple", "banana"]
fruits.append("cherry")
fruits.insert(1, "orange")
fruits.extend(["grape", "kiwi"])
list1 = [1, 2, 3]
list1.append([4, 5])
list2 = [1, 2, 3]
list2.extend([4, 5])
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
del fruits[0]
last = fruits.pop()
second = fruits.pop(0)
fruits.clear()
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana"))
print(fruits.count("banana"))
print("apple" in fruits)
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
numbers.sort(reverse=True)
numbers = [3, 1, 4, 1, 5]
sorted_nums = sorted(numbers)
words = ["banana", "pie", "Washington", "book"]
words.sort(key=len)
words.sort(key=str.lower)
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
reversed_nums = numbers[::-1]

List operations

아래 코드는 python를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
repeated = [1, 2] * 3
numbers = [3, 1, 4, 1, 5]
print(max(numbers), min(numbers), sum(numbers))

List comprehensions

아래 코드는 python를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
matrix = [[i * j for j in range(3)] for i in range(3)]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]

Copying lists

다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

list1 = [1, 2, 3]
list2 = list1
list2[0] = 100
print(list1)
list1 = [1, 2, 3]
list2 = list1.copy()
list3 = list1[:]
list4 = list(list1)
list2[0] = 100
print(list1, list2)
import copy
matrix = [[1, 2], [3, 4]]
matrix_copy = matrix.copy()
matrix_copy[0][0] = 100
print(matrix)
matrix_deep = copy.deepcopy(matrix)
matrix_deep[0][0] = 999
print(matrix, matrix_deep)

2. Dictionary

Basics

아래 코드는 python를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

person = {"name": "Alice", "age": 25, "city": "Seoul"}
print(person[name])
print(person.get("age"))
print(person.get("job", "N/A"))
person[job] = "Developer"
person[age] = 26
del person[city]
job = person.pop("job")

Dictionary methods

아래 코드는 python를 사용한 구현 예제입니다. 에러 처리를 통해 안정성을 확보합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

person = {"name": "Alice", "age": 25}
for key in person:
    print(key, person[key])
for key, value in person.items():
    print(f"{key}: {value}")
person.update({"city": "Seoul", "job": "Developer"})
person.setdefault("country", "KR")
last = person.popitem()

Dict comprehensions

아래 코드는 python를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

squares = {x: x**2 for x in range(5)}
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
names = ["Alice", "Bob", "Charlie"]
name_dict = {i: name for i, name in enumerate(names)}

Nested dicts

아래 코드는 python를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

users = {
    "user1": {"name": "Alice", "age": 25},
    "user2": {"name": "Bob", "age": 30},
}
print(users[user1][name])
name = users.get("user1", {}).get("name", "N/A")

defaultdict

아래 코드는 python를 사용한 구현 예제입니다. 필요한 모듈을 import하고. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

from collections import defaultdict
word_count = defaultdict(int)
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
for word in words:
    word_count[word] += 1
print(dict(word_count))
groups = defaultdict(list)
students = [("Alice", "A"), ("Bob", "B"), ("Carol", "A")]
for name, grade in students:
    groups[grade].append(name)
print(dict(groups))

3. Tuple

What is a tuple?

A tuple is ordered and immutable. Like a list, but you cannot change elements after creation. When to use:

  • Fixed data (coordinates, config)
  • Multiple return values from a function
  • Dict keys (must be hashable)

Creation and access

아래 코드는 python를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

point = (10, 20)
person = ("Alice", 25, "Seoul")
single = (42,)
coords = 10, 20, 30
empty = ()
numbers = tuple([1, 2, 3, 4, 5])
# person[1] = 26  # TypeError
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2), numbers.index(3))

Unpacking

아래 코드는 python를 사용한 구현 예제입니다. 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

name, age, city = ("Alice", 25, "Seoul")
def get_user():
    return "Alice", 25, "Seoul"
a, b = 1, 2
a, b = b, a
numbers = (1, 2, 3, 4, 5)
first, *rest, last = numbers

Tuple vs list

TupleList
MutableNoYes
Dict keyYesNo
MemoryLowerHigher
아래 코드는 python를 사용한 구현 예제입니다. 필요한 모듈을 import하고. 코드를 직접 실행해보면서 동작을 확인해보세요.
import sys
print(sys.getsizeof([1, 2, 3, 4, 5]))
print(sys.getsizeof((1, 2, 3, 4, 5)))
locations = {(10, 20): "A", (30, 40): "B"}

Mutable elements inside tuples

아래 코드는 python를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

tuple_with_list = (1, 2, [3, 4])
tuple_with_list[2].append(5)
print(tuple_with_list)
original = (1, 2, 3)
modified = original + (4, 5)

4. Set

What is a set?

A set is unordered and contains unique elements—like a mathematical set. 아래 코드는 python를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

fruits = {"apple", "banana", "cherry"}
empty = set()
# empty = {}  # this creates a dict!
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = set(numbers)
fruits.add("cherry")
fruits.update(["orange", "grape"])
fruits.remove("banana")
fruits.discard("kiwi")
item = fruits.pop()
fruits.clear()

Set operations

아래 코드는 python를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b, a.union(b))
print(a & b, a.intersection(b))
print(a - b, a.difference(b))
print(a ^ b, a.symmetric_difference(b))
c = {1, 2}
print(c.issubset(a), a.issuperset(c))
print(a.isdisjoint({7, 8, 9}))

Practical examples

Student grades

다음은 python를 활용한 상세한 구현 코드입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

students = [
    {"name": "Alice", "scores": [85, 90, 78]},
    {"name": "Bob", "scores": [92, 88, 95]},
    {"name": "Carol", "scores": [78, 82, 80]},
]
for student in students:
    avg = sum(student[scores]) / len(student[scores])
    if avg >= 90:
        grade = "A"
    elif avg >= 80:
        grade = "B"
    else:
        grade = "C"
    print(f"{student['name']}: avg {avg:.1f}, grade {grade}")

Word frequency

아래 코드는 python를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

text = """
Python is powerful. Python is easy.
Python is popular. Python is versatile.
"""
words = text.lower().replace(".", "").split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_words[:5]:
    print(f"  {word}: {count}")
print(f"Unique words: {len(set(words))}")

Shopping cart

다음은 python를 활용한 상세한 구현 코드입니다. 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

products = {
    "P001": {"name": "Laptop", "price": 1200},
    "P002": {"name": "Mouse", "price": 30},
    "P003": {"name": "Keyboard", "price": 80},
}
cart = {}
def add_to_cart(product_id, quantity=1):
    if product_id in products:
        cart[product_id] = cart.get(product_id, 0) + quantity
        print(f"Added {quantity}x {products[product_id]['name']}")
    else:
        print("Unknown product.")
def calculate_total():
    total = 0
    for product_id, quantity in cart.items():
        total += products[product_id][price] * quantity
    return total
add_to_cart("P001", 1)
add_to_cart("P002", 2)
add_to_cart("P003", 1)
print(f"Total: {calculate_total()}")

Complexity and choosing a type

OperationListTupleDictSet
Index accessO(1)O(1)
Key lookupO(1)
in (membership)O(n)O(n)O(1) keysO(1)

Common mistakes

  1. {} is a dict, not an empty set — use set().
  2. Assignment copies references — use .copy() or slicing for shallow copies; deepcopy for nested structures.
  3. Missing keys — use .get() or check in before dict[key].
  4. Single-element tuple — needs a comma: (42,).
  5. Sets are not subscriptable — convert to list() or sorted() for ordering.

Summary

TypeOrderedDuplicatesMutableTypical use
ListYesYesYesSequences you change
TupleYesYesNoFixed records, keys
DictYes (3.7+)Keys uniqueYesFast lookup by key
SetNoNoYesUniqueness, set math

Next steps


... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3