Python Data Types | Lists· Dictionaries
이 글의 핵심
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](/en/blog/algorithm-series-01-array-list/, [hash tables](/en/blog/algorithm-series-03-hash-table/, and C++ [map vs unordered_map](/en/blog/cpp-comparison-02-map-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
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
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
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
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
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
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
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
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
users = {
"user1": {"name": "Alice", "age": 25},
"user2": {"name": "Bob", "age": 30},
}
print(users[user1][name])
name = users.get("user1", {}).get("name", "N/A")
defaultdict
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
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
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
| Tuple | List | |
|---|---|---|
| Mutable | No | Yes |
| Dict key | Yes | No |
| Memory | Lower | Higher |
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
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.
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
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
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
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
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
| Operation | List | Tuple | Dict | Set |
|---|---|---|---|---|
| Index access | O(1) | O(1) | — | — |
| Key lookup | — | — | O(1) | — |
in (membership) | O(n) | O(n) | O(1) keys | O(1) |
Common mistakes
{}is a dict, not an empty set — useset().- Assignment copies references — use
.copy()or slicing for shallow copies;deepcopyfor nested structures. - Missing keys — use
.get()or checkinbeforedict[key]. - Single-element tuple — needs a comma:
(42,). - Sets are not subscriptable — convert to
list()orsorted()for ordering.
Summary
| Type | Ordered | Duplicates | Mutable | Typical use |
|---|---|---|---|---|
| List | Yes | Yes | Yes | Sequences you change |
| Tuple | Yes | Yes | No | Fixed records, keys |
| Dict | Yes (3.7+) | Keys unique | Yes | Fast lookup by key |
| Set | No | No | Yes | Uniqueness, set math |
Next steps
- [Python functions](/en/blog/python-series-04-functions/
- Python comprehensions (if available)
- [Python classes](/en/blog/python-series-05-classes/
Related posts
- [Python environment setup](/en/blog/python-series-01-environment-setup/
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. Master Python built-in types: list, dict, tuple, set. Slicing, comprehensions, copying, defaultdict, and performance tip… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. Python 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- [Python Basics | Variables· Operators](/en/blog/python-series-02-basic-syntax/
- [Python Functions | Parameters· Return Values](/en/blog/python-series-04-functions/
- [Hash Table | O(1) Search Data Structure Complete Guide](/en/blog/algorithm-series-03-hash-table/
- [Arrays and Lists](/en/blog/algorithm-series-01-array-list/
- [C++ map vs unordered_map: Performance, Complexity, and How](/en/blog/cpp-comparison-02-map-unordered-map/
이 글에서 다루는 키워드 (관련 검색어)
Python, Data Types, List, Dict, Tuple, Set, Beginner 등으로 검색하시면 이 글이 도움이 됩니다.