Site

Lists — Python list Operations

Tutorial S2  •  Python / Learn

S2.0 What This Teaches

This tutorial covers Python's built-in list type:

S2.1 Creating and Initializing

# Literal syntax
numbers = [1, 2, 3, 4, 5]
mixed   = [1, "two", 3.0, True]   # lists can hold any types
empty   = []

# list() constructor
from_range  = list(range(10))      # [0, 1, 2, ..., 9]
from_string = list("hello")        # ['h', 'e', 'l', 'l', 'o']
from_tuple  = list((1, 2, 3))      # [1, 2, 3]

# Comprehension
squares = [x ** 2 for x in range(1, 6)]  # [1, 4, 9, 16, 25]

S2.2 Indexing and Slicing

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

print(fruits[0])     # 'apple'
print(fruits[-1])    # 'elderberry'
print(fruits[1:3])   # ['banana', 'cherry']
print(fruits[:2])    # ['apple', 'banana']
print(fruits[2:])    # ['cherry', 'date', 'elderberry']
print(fruits[::2])   # ['apple', 'cherry', 'elderberry']

# Slices return new lists - they don't modify the original
reversed_copy = fruits[::-1]

S2.3 Adding and Removing

lst = ["a", "b", "c"]

lst.append("d")          # ["a", "b", "c", "d"]
lst.insert(1, "x")       # ["a", "x", "b", "c", "d"]
lst.extend(["e", "f"])   # appends multiple items

lst.remove("x")          # removes first "x" - ValueError if not found
popped = lst.pop()       # removes and returns last element
popped2 = lst.pop(0)     # removes and returns element at index 0
del lst[1]               # removes element at index (no return)

lst.clear()              # removes all elements
print(lst)               # []

S2.4 Searching and Testing

nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]

print(3 in nums)            # True
print(7 in nums)            # False
print(nums.index(5))        # 4 - first occurrence (ValueError if missing)
print(nums.count(1))        # 2 - number of occurrences
print(len(nums))            # 9
print(min(nums), max(nums)) # 1 9
print(sum(nums))            # 36

S2.5 Sorting

words = ["banana", "apple", "cherry", "date"]

# sort() modifies in place; returns None
words.sort()
print(words)   # ['apple', 'banana', 'cherry', 'date']

words.sort(reverse=True)   # descending

words.sort(key=len)        # sort by string length

# sorted() returns a new list; original unchanged
original = [3, 1, 4, 1, 5]
new_sorted = sorted(original)            # ascending
new_sorted = sorted(original, reverse=True)  # descending
print(original)    # [3, 1, 4, 1, 5] - unchanged
Prefer sorted() when you need to keep the original, or when sorting an iterable that is not a list.

S2.6 Copying Lists

original = [1, 2, 3]

# Shallow copies - top-level elements are copied
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)

copy1.append(4)
print(original)   # [1, 2, 3] - unaffected

# Deep copy for nested structures
import copy
nested = [[1, 2], [3, 4]]
deep = copy.deepcopy(nested)
deep[0].append(99)
print(nested)   # [[1, 2], [3, 4]] - unaffected

S2.7 Example - All Together

# Lists - student grade tracker with sort and filter.

students = [
    ("Alice", 92), ("Bob", 78), ("Carol", 95),
    ("Dave", 83), ("Eve", 78)
]

students.sort(key=lambda s: s[1], reverse=True)

print("Ranked:")
for rank, (name, score) in enumerate(students, 1):
    print(f"  {rank}. {name:<8} {score}")

passing = [s for s in students if s[1] >= 80]
print(f"\nPassing: {len(passing)}")
Expected output:
Ranked:
  1. Carol    95
  2. Alice    92
  3. Dave     83
  4. Bob      78
  5. Eve      78

Passing: 3

S2.8 Exercise

Exercise
  • Generate a list of 20 random integers (1-100) using random.randint. Print the 5 largest.
  • Remove duplicates while preserving order (hint: use a set to track seen values). Compare to using list(set(...)) which does not preserve order.
  • Write a function flatten(nested) that converts a list of lists into a single flat list using a list comprehension.

S2.9 Common Mistakes

Assigning instead of copying

a = [1, 2, 3]
b = a           # b is the same list, not a copy
b.append(4)
print(a)        # [1, 2, 3, 4] - a is also changed!
b = a.copy()    # make an independent shallow copy

Modifying a list while iterating over it

nums = [1, 2, 3, 4, 5]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)   # skips elements - unpredictable!
# Correct: iterate a copy or use a comprehension
nums = [n for n in nums if n % 2 != 0]

sort() vs sorted() confusion

sort() modifies the list in place and returns None. Assigning result = lst.sort() gives you None, not the sorted list. Use sorted(lst) when you need to assign the result.

S2.10 Key Terms

TermMeaning
listMutable ordered sequence; elements accessed by integer index
appendAdds one element to the end; O(1) amortized
extendAppends all elements of an iterable; O(k)
insertInserts before a given index; O(n) due to shifting
popRemoves and returns an element; O(1) from end, O(n) from middle
sortIn-place sort using Timsort; accepts key and reverse arguments
sortedReturns a sorted copy of any iterable
slicelst[start:stop:step] - produces a new list