🐍 Python Topic Library

Python Lists — Methods, Slicing & Comprehensions

Lists are Python's workhorse: ordered, changeable collections that hold anything. If you learn one data structure deeply, make it this one.

⚡ Quick Answer

Create with brackets: scores = [90, 85, 77]. Add with .append(), remove with .remove() or .pop(), sort with .sort(), measure with len(). Lists keep order and allow duplicates.

§Creating & accessing

basics.py
scores = [90, 85, 77]
mixed  = [1, "two", 3.0, True]   # any types together
empty  = []

print(scores[0])     # 90 — first (index 0!)
print(scores[-1])    # 77 — last
print(len(scores))   # 3
print(85 in scores)  # True

§Adding & removing

modify.py
todo = ["learn python"]
todo.append("build project")        # add to end
todo.insert(0, "wake up")           # add at position
todo.extend(["sleep", "repeat"])    # add many

todo.remove("sleep")     # remove by VALUE (first match)
last = todo.pop()        # remove & return last item
first = todo.pop(0)      # remove & return by INDEX
del todo[0]              # delete by index, no return

§Sorting & reversing

sorting.py
nums = [3, 1, 4, 1, 5]
nums.sort()                     # in place: [1, 1, 3, 4, 5]
nums.sort(reverse=True)         # [5, 4, 3, 1, 1]

words = ["banana", "Apple", "cherry"]
words.sort(key=str.lower)       # case-insensitive sort

top3 = sorted(nums)[:3]         # sorted() = NEW list, original untouched

§Slicing & copying

Slices work exactly like string slices — and they're also the safe way to copy.

slicing.py
nums = [10, 20, 30, 40, 50]
print(nums[1:4])    # [20, 30, 40]
print(nums[::2])    # [10, 30, 50] — every 2nd

copy = nums[:]       # REAL copy
alias = nums         # NOT a copy — same list, two names!
alias.append(60)
print(nums)          # [10, 20, 30, 40, 50, 60] — surprise!

§List comprehensions — Python's superpower

comprehension.py
squares = [n * n for n in range(1, 6)]
print(squares)                    # [1, 4, 9, 16, 25]

evens = [n for n in range(20) if n % 2 == 0]

names = ["ada", "grace", "alan"]
caps = [n.title() for n in names] # ['Ada', 'Grace', 'Alan']

§Common Mistakes to Avoid

🚨 Watch out for these
  • Copying with = instead of [:]b = a makes two names for ONE list — changes through either name affect both. Use b = a[:] or a.copy()
  • IndexError on empty listsitems[0] crashes when the list is empty — check if items: first
  • Expecting sort() to return the listx = nums.sort() sets x to None! sort() works in place; use sorted(nums) for a new list

§Frequently Asked Questions

What's the difference between append() and extend()?

append(x) adds x as ONE item (even if x is a list); extend(xs) adds each element of xs individually.

How do I copy a list in Python?

Use new = old[:] or new = old.copy(). Plain new = old only creates a second name for the same list.

What is a list comprehension?

A one-line expression that builds a list: [n*n for n in range(5)]. It replaces a 3-line for-loop with clearer, faster code.

Can a Python list hold different types?

Yes — [1, "two", 3.0, True] is valid. In practice, keeping one type per list makes code easier to reason about.

🎓 Want to master Python properly?This reference covers one topic — the full free course takes you from zero to projects, with quizzes and a certificate.
Start the Free Python Course →

§Related Python Topics

← StringsDictionaries →