ASAmol Shukla
Projects
Courses
Prompts
Skills
Contact
Resume
Course Outline
Syllabus Overview

Complete Python Course: From Zero to Professional

Courses/Complete Python Course: From Zero to Professional/Lesson 8: Lists & Tuples
40 mins lesson duration•8 mins read

Lesson 8: Lists & Tuples

Mutable lists, immutable tuples, slicing, sorting, and common list methods.

Lists — Your All-Purpose Container

A list is an ordered, mutable collection. "Mutable" means you can add, remove, or change items after creation. Lists are the workhorse of Python — you will use them in almost every program you write.

fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]     # lists can hold mixed types
empty = []

Think of a list as a row of labeled boxes — each box holds a value, the boxes are in a fixed order, and you can put things in, take things out, or swap contents at any time. That flexibility is why lists dominate everyday Python.

What You'll Learn in This Lesson

  • Create and manipulate lists with the essential methods
  • Understand the difference between mutable lists and immutable tuples
  • Slice and sort like a professional
  • Use tuple unpacking for clean code

Essential List Methods

Method What it does
append(x) Add one item to the end
extend([...]) Add many items (like + but in place)
insert(i, x) Insert x at position i
remove(x) Remove the first matching item
pop(i) Remove and return the item at i (default: last)
sort() Sort in place (mutates the list)
index(x) Find the position of x
count(x) How many times x appears
copy() Return a shallow copy
clear() Remove everything
len(lst) Number of items (built-in function)
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "blueberry")
print(fruits)   # ['apple', 'blueberry', 'banana', 'cherry', 'date']
last = fruits.pop()
print(last)     # date

append vs extend — the classic confusion:

Code Result
a = [1, 2]; a.append([3, 4]) [1, 2, [3, 4]] — nested list added as ONE item
b = [1, 2]; b.extend([3, 4]) [1, 2, 3, 4] — items flattened into the list

Mental model: append adds one box to the row (whatever is inside it, even another row). extend unpacks a whole tray and shelves each item separately.


Sorting — In Place vs New List

Python has two sorting tools — confusing at first, but simple once you know:

Tool Mutates? Returns Use when
list.sort() Yes None You want to change the original
sorted(list) No New list You want to keep the original
numbers = [42, 7, 19, 3]
numbers.sort()
print(numbers)                              # [3, 7, 19, 42]
print(sorted([3, 1, 2], reverse=True))      # [3, 2, 1] — original untouched

Both accept a key for custom ordering and reverse=True for descending order:

names = ["python", "ai", "machine learning"]
print(sorted(names, key=len))   # ['ai', 'python', 'machine learning']

The key receives each item and returns the value used for comparison — sort by length, by last letter, by a dict field, by anything. This is one of the most-used patterns in professional Python.

Memory note: sorted() builds a new list, so for a huge list where you don't need the original, .sort() is more memory-friendly.


Tuples — Locked Lists

A tuple (1, 2, 3) is immutable — once created, it can never change. No append, no insert, no reassignment of items.

point = (3, 4)
# point[0] = 9   # TypeError: 'tuple' object does not support item assignment

Use tuples for fixed data: coordinates, colors, RGB values, configuration constants, function return values. They are faster and safer than lists for data that must not change.

List [...] Tuple (...)
Mutable ✅ Yes ❌ No
Speed Slower Faster
Use for Dynamic collections Fixed records
Example Shopping cart A point (x, y)

Note: a single-element tuple needs a trailing comma: (5,) — otherwise (5) is just the number 5 in parentheses.

Tuples as dict keys: because tuples are immutable (and hashable), they can serve as dictionary keys — for example, a (latitude, longitude) pair mapping to a city name. Lists cannot.


Tuple Unpacking — Elegant Swaps

Assigning a tuple to multiple variables "unpacks" it:

point = (3, 4)
x, y = point          # x=3, y=4
print(x, y)           # 3 4

a, b = 5, 10
a, b = b, a           # swap without a temp variable!
print(a, b)           # 10 5

Functions that return multiple values use tuples under the hood — unpacking is how you grab them.

Extended unpacking with * handles uneven lengths:

first, *rest = [1, 2, 3, 4]
print(first)   # 1
print(rest)    # [2, 3, 4]

head, *middle, tail = "Python"
print(head, middle, tail)   # P ['y', 't', 'h', 'o'] n

Slicing Works on Both

Everything you learned about string slicing (Lesson 3) works on lists and tuples:

data = [10, 20, 30, 40, 50]
print(data[1:4])      # [20, 30, 40]
print(data[::-1])     # [50, 40, 30, 20, 10] — reversed
print(data[::2])      # [10, 30, 50]

Copy with slicing: copy = original[:] creates a real copy. We will see why this matters in Lesson 11.


Real-World List Patterns

  • Stack (last-in, first-out): push = lst.append(x), pop = lst.pop().
  • Queue (first-in, first-out): enqueue = lst.append(x), dequeue = lst.pop(0) (for big queues, collections.deque is faster — Lesson 10).
  • Comprehension building: [f(x) for x in data] (Lesson 7).
  • In-place unique: list(set(items)) (Lesson 9).
  • Max / min / sum: max(lst), min(lst), sum(lst) — built-ins that work directly on lists.

Common Mistakes to Avoid

  • Mistake: fruits[5] on a 3-item list — Fix: check len(fruits); the last index is always len - 1.
  • Mistake: Expecting sorted() to change the original — Fix: sorted() returns a new list; .sort() mutates.
  • Mistake: Writing (5) and expecting a tuple — Fix: add the trailing comma: (5,).
  • Mistake: b = a thinking it copies the list — Fix: b = a[:] or b = a.copy() (see Lesson 11).
  • Mistake: append when you meant extend — Fix: use extend to merge item-by-item.
  • Mistake: Trying to change a tuple — Fix: if you need mutability, use a list.

Professional Tips & Tricks

  • Use sort(key=...) for custom ordering, e.g. names.sort(key=len).
  • Prefer tuples for function return values — they are lighter and clearly 'fixed'.
  • Copy lists with slicing: copy = original[:] — this avoids mutating the original.
  • Use extended unpacking first, *rest = items to peel off the head of a list.

Key Takeaways

  • Lists are ordered and mutable; tuples are ordered and immutable.
  • append/extend/insert/pop are your core list tools.
  • .sort() mutates; sorted() returns a new list.
  • Tuple unpacking (a, b = b, a) makes swapping trivial.
  • Slicing works identically on strings, lists, and tuples.
  • Tuples are hashable — they can be dict keys; lists cannot.

Next up: Sets & dictionaries — fast lookups and key-value data.

Interactive Lesson Code Snippet
# Lists: mutable and flexible
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "blueberry")
print("After adds:", fruits)

# Sorting (in place vs new list)
numbers = [42, 7, 19, 3]
numbers.sort()
print("Sorted in place:", numbers)
print("Descending:", sorted(numbers, reverse=True))

# Tuples: immutable
point = (3, 4)
x, y = point          # tuple unpacking
print("Coordinates:", x, y)

# Tuples protect data
colors = ("red", "green", "blue")
print("First color:", colors[0], "| Count:", len(colors))
Language: python

Lesson Code (Python)

# Lists: mutable and flexible
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "blueberry")
print("After adds:", fruits)

# Sorting (in place vs new list)
numbers = [42, 7, 19, 3]
numbers.sort()
print("Sorted in place:", numbers)
print("Descending:", sorted(numbers, reverse=True))

# Tuples: immutable
point = (3, 4)
x, y = point          # tuple unpacking
print("Coordinates:", x, y)

# Tuples protect data
colors = ("red", "green", "blue")
print("First color:", colors[0], "| Count:", len(colors))

Console Output

After adds: ['apple', 'blueberry', 'banana', 'cherry', 'date']
Sorted in place: [3, 7, 19, 42]
Descending: [42, 19, 7, 3]
Coordinates: 3 4
First color: red | Count: 3

Code Visualization Tips

  • 🧠Draw a list as a row of boxes with index numbers underneath (0, 1, 2...).
  • 🧠For slicing, place your fingers at the two boundary positions and read what is between them.
  • 🧠Compare lists vs tuples as a backpack you can repack vs a sealed box you cannot open to change.

Professional Tips & Tricks

  • ⚡Use sort(key=...) for custom ordering, e.g. names.sort(key=len).
  • ⚡Prefer tuples for function return values — they are lighter and clearly 'fixed'.
  • ⚡Copy lists with slicing: copy = original[:] — this avoids mutating the original.

Python Code Judge & Practice Arena

LeetCode Style

Run real Python 3.12 WebAssembly code directly in your browser against automated test suites.

Solved:0 / 20
0 / 370 XP
Challenges:
Problem 1 of 20

Problem 1: Deduplicate & Sort List 1

Easy+10 XP
Write a function `unique_sorted_1(items)` that returns a new sorted list containing unique elements without duplicates.
Sample Test Cases:
Input: unique_sorted_1([3, 1, 2, 3, 1, 4])
Expected: [1, 2, 3, 4]
Input: unique_sorted_1([10, 5, 20])
Expected: [5, 10, 20]
main.pyPython 3.12 (WASM)
1
2
3
4
5
6
7
8
9
10
11
12
Press Run Code to test or Submit to verify test cases

Test Your Knowledge

Instant feedback

Quick Check: Lesson 8: Python Lists & Tuples in Depth

1 / 20
What will the following list append vs extend code print? a = [1, 2] a.append([3, 4]) b = [1, 2] b.extend([3, 4]) print(len(a), len(b))

Up next · Continue learning

Sets & Dictionaries

Unordered sets for lightning-fast membership, and key-value dictionaries for real-world data.

9 mins read45 mins
Start next lesson
Previous: Comprehensions — Clean, Fast LoopsNext: Sets & Dictionaries
Made withbyAmol Shukla·amolshukla.online
ASAmol Shukla

AI Developer, Trainer & Agentic AI Expert building practical learning systems and real-world AI applications.

Explore

  • Projects
  • Courses
  • Prompts
  • Skills
  • Contact
  • Experience
  • Blogs

Connect

  • Resume
  • Contact
© 2026 Amol Shukla·Created withbyamolshukla.online
Back to top