Python Lists
Create, modify, slice, and sort Python lists with clear explanations and examples.
What is a List?
A list is Python's most versatile data structure — an ordered, mutable collection
that can hold any mix of types. "Ordered" means items stay in the position you put them.
"Mutable" means you can add, remove, or change items after creation. Lists use square brackets
[] and are one of the most frequently used structures in Python code.
fruits = ["apple", "banana", "cherry"] mixed = ["hello", 42, True, 3.14] # any types print(fruits[0]) # first item print(fruits[-1]) # last item print(len(fruits)) # number of items
apple cherry 3
Adding and Removing Items
append() adds to the end. insert(index, val) adds at a specific position.
remove(val) deletes the first occurrence of a value (raises ValueError if not found).
pop() removes and returns the last item (or a specific index if given) — useful
when you need the removed value.
items = ["a", "b", "c"] items.append("d") # add to end print(items) items.insert(1, "x") # insert at position 1 print(items) items.remove("x") # remove by value print(items) last = items.pop() # remove and return last print(f"Popped: {last} | Left: {items}")
['a', 'b', 'c', 'd'] ['a', 'x', 'b', 'c', 'd'] ['a', 'b', 'c', 'd'] Popped: d | Left: ['a', 'b', 'c']
Slicing
Slicing extracts a portion using list[start:stop:step] — same syntax as strings.
The result is a new list; the original is unchanged. Leave start empty to
begin from the start; leave stop empty to go to the end.
n = [0, 1, 2, 3, 4, 5, 6] print(n[2:5]) # indices 2, 3, 4 print(n[:3]) # first 3 print(n[4:]) # from index 4 to end print(n[::-1]) # reversed copy print(n[::2]) # every 2nd item
[2, 3, 4] [0, 1, 2] [4, 5, 6] [6, 5, 4, 3, 2, 1, 0] [0, 2, 4, 6]
Sorting
list.sort() modifies the list in place. sorted(list) leaves the
original untouched and returns a new sorted list. Both accept reverse=True for descending
order.
nums = [3, 1, 4, 1, 5, 9] nums.sort() print(nums) orig = [3, 1, 4] s = sorted(orig) # orig stays unchanged print(orig, "→", s)
[1, 1, 3, 4, 5, 9] [3, 1, 4] → [1, 3, 4]
b = a where a is a list, both variables point to the same list. Use b = a.copy() or b = a[:] to get an independent copy.🧠 Quick Check
Which method adds an item to the end of a list?