C
Python/Intro/Lesson 04

List

1 hr·theory
This chapter
3/7
Python

List

🎯 After reading this lesson

After finishing this lesson, you will be able to confidently do the following 3 things.

  • ✅ List slicing + comprehension
  • ✅ Choosing list vs tuple + deep copy (copy.deepcopy)
  • ✅ sort vs sorted (whether the original is modified)

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

8 core list concepts — code + output

list = a data structure that is ordered + mutable + can hold any type. The most frequently used data structure in Python.


1. Creating a list

python
numbers = [1, 2, 3, 4, 5]
names = ["Gildong Hong", "Mongryong Lee", "Chunhyang Seong"]
mixed = [1, "two", 3.0, True]      # Mixing types is OK
empty_list = []

print(len(numbers))     # 5 (count)
print(type(numbers))    # <class 'list'>

2. Indexing — starts at 0

python
fruits = ["apple", "pear", "persimmon", "tangerine"]

print(fruits[0])       # "apple"  (first)
print(fruits[-1])      # "tangerine"   (last) ← Negative numbers OK
print(fruits[-2])      # "persimmon"   (second from last)

⚠️ fruits[10]IndexError: list index out of range


3. Slicing — [start:end]

python
numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])     # [20, 30, 40]   ← From 1 up to just before 4
print(numbers[:3])      # [10, 20, 30]   ← From start up to just before 3
print(numbers[2:])      # [30, 40, 50]   ← From 2 to the end
print(numbers[::-1])    # [50, 40, 30, 20, 10]   ← Reversed

Key point: The end index is exclusive (not included). [::-1] is the idiom for reversing a list.


4. Adding and removing

python
fruits = ["apple", "pear"]

fruits.append("persimmon")       # ["apple", "pear", "persimmon"]
fruits.insert(1, "grape")  # ["apple", "grape", "pear", "persimmon"]
fruits.remove("pear")       # ["apple", "grape", "persimmon"]
last_fruit = fruits.pop()    # last_fruit = "persimmon", list = ["apple", "grape"]

print(fruits)

5. Searching and checking

python
fruits = ["apple", "pear", "persimmon"]

print("pear" in fruits)         # True
print("grape" in fruits)       # False
print(fruits.index("persimmon"))     # 2 (which index?)
print(fruits.count("apple"))   # 1 (how many?)

6. Sorting

python
numbers = [3, 1, 4, 1, 5, 9, 2]

numbers.sort()                # Modifies original
print(numbers)                # [1, 1, 2, 3, 4, 5, 9]

original = [3, 1, 4]
sorted_list = sorted(original)         # Returns a new list
print(original, sorted_list)          # [3, 1, 4] [1, 3, 4]

numbers.sort(reverse=True)
print(numbers)                # [9, 5, 4, 3, 2, 1, 1]

sort() = modifies the original / sorted(x) = returns a new list.


7. Iteration (for)

```python
fruits = ["apple", "pear", "persimmon"]

for fruit in fruits:
print(f

💻 Shopping cart manipulation + slicing + sorting
# ===== Input: Shopping Cart =====
cart = ["Apple", "Banana", "Milk"]

# ===== Process: Add/Remove Items =====
cart.append("Egg")         # Add to end
cart.append("Tofu")
print(f"After adding: {cart}")    # ['Apple', 'Banana', 'Milk', 'Egg', 'Tofu']

cart.remove("Banana")        # Delete by value
last = cart.pop()           # Pop last element (remove + return)
print(f"After removing: {cart}")    # ['Apple', 'Milk', 'Egg']
print(f"Popped item: {last}")  # Tofu

# ===== Index Access =====
print(cart[0])              # Apple (first)
print(cart[-1])             # Egg (last)

# ===== Slicing: [start:end] end is exclusive =====
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])         # [20, 30, 40]
print(numbers[:3])          # [10, 20, 30] (3 items from start)
print(numbers[2:])          # [30, 40, 50] (from 3rd to end)

# ===== Length and Sorting =====
scores = [88, 72, 95, 61, 83]
print(f"Number of items: {len(scores)}")        # 5
print(f"Sorted: {sorted(scores)}")        # [61, 72, 83, 88, 95]
print(f"Max value: {max(scores)}")         # 95
print(f"Sum: {sum(scores)}")           # 399

💡 Key points

1. Negative index: -1 refers to the last element
2. Slicing: [start:end:step]
3. sort() modifies the original; sorted() returns a new list

Python basic data structures: a list is an ordered mutable collection, a tuple is immutable, a dictionary holds key-value pairs, and a set holds unique values. Use list comprehension [x for x in lst if cond] for concise creation. Use dict.get(key, default) to safely retrieve values. The collections module provides: Counter, defaultdict, deque, OrderedDict.

🐍 Try running it — List

Run the concepts above as actual code. The fastest way to learn is to change the values and see how it behaves firsthand.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Knowing the concepts in this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' you make vocabulary-driven requests — that is the starting point for saving tokens.

  • 'Convert this for + append into a list comprehension'
  • 'Check whether deep copy (copy.deepcopy) is needed in this code'

Why this saves tokens

Without knowing the concepts, even after receiving an AI answer you have to ask 'What does that mean?' again. That follow-up question is what eats your tokens. Learn the concept once, and the conversation ends in one round.

Mastering Lists - Python