Lists (append, sort, pop, slice, in, enumerate) - Python Tutorial for Beginners #8
Video: Lists (append, sort, pop, slice, in, enumerate) - Python Tutorial for Beginners #8 by Taught by Celeste AI - AI Coding Coach
Python Lists: append, sort, pop, slice
[]for empty.[1, 2, 3]literal..append(x)to add,.pop()to remove. Slicinglst[1:4]. Lists are mutable and ordered — Python's go-to sequence type.
Lists are Python's most-used container. Mutable, ordered, can hold any types. Backed by a dynamic array internally — fast random access and append.
Creating lists
colors = ["red", "green", "blue"]
mixed = [42, "hello", 3.14, True]
empty = []
print(colors) # ['red', 'green', 'blue']
print(mixed) # [42, 'hello', 3.14, True]
Square brackets, comma-separated. Items can be any type, mixed.
Indexing
print(colors[0]) # 'red'
print(colors[-1]) # 'blue' (last)
print(colors[-2]) # 'green' (second to last)
0-indexed. Negative indices count from the end.
colors[10] raises IndexError. To safely access, use len(colors) or try/except.
Slicing
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[:3]) # [10, 20, 30]
print(nums[2:]) # [30, 40, 50]
print(nums[::2]) # [10, 30, 50] — step 2
print(nums[::-1]) # [50, 40, 30, 20, 10] — reversed
lst[start:end:step]. start inclusive, end exclusive. Defaults: 0, len, 1.
Slicing returns a new list. Original unchanged.
append, insert, extend
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
fruits.insert(1, "blueberry")
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry']
fruits.extend(["date", "elderberry"])
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry']
.append(x)— add to end. O(1)..insert(i, x)— add at index i. O(n) (shifts)..extend(iterable)— add all from another iterable. O(k).
a + b creates a new list; a.extend(b) modifies a in place.
remove, pop, del
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana") # remove first occurrence by value
print(fruits) # ['apple', 'cherry']
last = fruits.pop() # remove and return last
print(last, fruits) # cherry, ['apple']
first = fruits.pop(0) # remove and return at index
print(first, fruits) # apple, []
# del statement
fruits = ["a", "b", "c", "d"]
del fruits[1] # remove index 1
print(fruits) # ['a', 'c', 'd']
del fruits[0:2] # remove a slice
print(fruits) # ['d']
.remove(value) finds first match and removes. .pop() returns the removed value.
del is a statement, not a method. Removes by index or slice.
sort and sorted
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.sort() # in-place, ascending
print(nums) # [1, 1, 2, 3, 4, 5, 6, 9]
nums.sort(reverse=True) # in-place, descending
print(nums) # [9, 6, 5, 4, 3, 2, 1, 1]
# sorted returns a new list, doesn't mutate
original = [3, 1, 2]
new = sorted(original)
print(original, new) # [3, 1, 2] [1, 2, 3]
.sort() mutates; sorted(lst) returns new sorted list.
Sort by custom key:
words = ["banana", "apple", "cherry"]
words.sort(key=len) # sort by length
words.sort(key=str.lower) # case-insensitive
people = [("Alice", 30), ("Bob", 25)]
people.sort(key=lambda p: p[1]) # by age
key=fn provides a key function. Each element is mapped through fn; sort by the result.
reverse
nums = [1, 2, 3]
nums.reverse() # in-place
print(nums) # [3, 2, 1]
# Or with reversed()
nums = [1, 2, 3]
new = list(reversed(nums))
print(new) # [3, 2, 1]
.reverse() mutates; reversed(lst) returns an iterator.
in: membership
colors = ["red", "green", "blue"]
print("red" in colors) # True
print("yellow" in colors) # False
print("yellow" not in colors) # True
x in lst is O(n). For frequent membership checks on large data, use a set (lesson 9).
Concatenation and repetition
a = [1, 2]
b = [3, 4]
print(a + b) # [1, 2, 3, 4]
print(a * 3) # [1, 2, 1, 2, 1, 2]
zeros = [0] * 5 # [0, 0, 0, 0, 0]
+ concatenates; * repeats. Useful for initialization ([0] * n).
Gotcha for nested: [[0] * 3] * 3 creates 3 references to the same inner list. Mutate one and they all change. Use a comprehension:
matrix = [[0] * 3 for _ in range(3)] # 3 independent rows
Common methods summary
| Method | Effect | Returns | Mutates? |
|---|---|---|---|
append(x) |
Add to end | None | Yes |
insert(i, x) |
Insert at i | None | Yes |
extend(it) |
Add all | None | Yes |
remove(x) |
Remove first match | None | Yes |
pop([i]) |
Remove and return | item | Yes |
clear() |
Remove all | None | Yes |
sort() |
Sort | None | Yes |
reverse() |
Reverse | None | Yes |
index(x) |
Find first occurrence | int | No |
count(x) |
Count occurrences | int | No |
copy() |
Shallow copy | list | No |
Copying lists
a = [1, 2, 3]
b = a # not a copy! same list
b.append(4)
print(a) # [1, 2, 3, 4] — also changed
# Real copy:
b = a.copy() # method
b = a[:] # slice trick
b = list(a) # constructor
import copy
b = copy.deepcopy(a) # deep copy (recursive)
a.copy() is shallow — top-level copy, but inner mutable items are shared. For nested structures, use copy.deepcopy.
List comprehensions (preview)
squares = [x * x for x in range(10)]
evens = [x for x in nums if x % 2 == 0]
upper = [s.upper() for s in strings]
Compact way to build a new list from an iterable. Lesson 14 covers them in depth.
Common stumbles
Modifying while iterating. for x in lst: if cond: lst.remove(x) — items skipped. Iterate a copy.
a = b for "copy." Both names point to the same list. Use a = b.copy() or a = b[:].
[[0] * n] * m creating shared rows. Use [[0] * n for _ in range(m)].
pop() empty list. Raises IndexError. Check first or wrap in try/except.
Index errors. lst[len(lst)] is past the end. Use lst[-1] for last item.
Sorting mixed types. [1, "a"] can't be sorted (no < between int and str). Either type-uniform or use key=.
What's next
Lesson 9: tuples and sets. Immutable cousin of lists; unordered uniqueness.
Recap
Lists: [1, 2, 3], mutable, ordered, any types. Index with [i], slice with [start:end:step]. Add: .append, .insert, .extend. Remove: .remove, .pop, del. Sort: .sort() (mutates), sorted() (new list); key= for custom. in for membership (O(n)). [0] * n for fast init; for nested, comprehension. Copy with .copy() or [:].
Next lesson: tuples and sets.