0%

9- Lists in Python

A list is an ordered collection of items. You can change it, add to it, remove from it, and loop through it. Lists are everywhere in Python.

A list is a collection of items in a specific order. You can put anything inside a list: numbers, strings, even other lists. You can change lists after creating them. You can add items, remove items, or rearrange them. Think of a list as a shopping cart. You start empty. You add apples, then bread, then milk. You change your mind and remove the milk. You insert eggs between apples and bread. A list lets you do all of this. Lists are one of the most versatile and commonly used data structures in Python. Mastering them will change how you code.

🕯️ Magic Note

Lists are mutable (you can change them), ordered (items keep their position), and can contain mixed types (a list can hold numbers, strings, and booleans together). This flexibility makes lists the Swiss Army knife of Python collections.

Creating Lists
Use square brackets [] to create a list. Separate items with commas.

Python

# Empty list

empty = []

# List of numbers

numbers = [1, 2, 3, 4, 5]

# List of strings

fruits = [“apple”, “banana”, “cherry”]

# Mixed types

mixed = [42, “hello”, 3.14, True]

# List can contain other lists (nested)

nested = [[1, 2], [3, 4], [5, 6]]

# Using the list() constructor

chars = list(“abc”) # [‘a’, ‘b’, ‘c’]

range_list = list(range(5)) # [0, 1, 2, 3, 4]

💡 Use list() to convert other sequences (like strings or tuples) into lists. Use square brackets [] to create a new list from scratch. Most of the time, you will use square brackets.
Accessing Items by Index
Like strings, lists use zero-based indexing. The first item is at index 0. Negative indices count from the end.

Python

fruits = [“apple”, “banana”, “cherry”, “date”, “elderberry”]

# Index: 0 1 2 3 4

# Negative: -5 -4 -3 -2 -1

print(fruits[0]) # apple

print(fruits[2]) # cherry

print(fruits[-1]) # elderberry (last item)

print(fruits[-2]) # date (second last)

⚠️ IndexError occurs when you try to access an index that does not exist. For a list with 5 items, valid indices are -5 through 4. fruits[5] or fruits[-6] will crash your program.
List Slicing
Slicing extracts a portion of a list. The syntax is list[start:end:step]. It returns a new list.

Python

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[2:6]) # [2, 3, 4, 5] (indices 2 through 5)

print(numbers[:4]) # [0, 1, 2, 3] (start omitted → beginning)

print(numbers[6:]) # [6, 7, 8, 9] (end omitted → end)

print(numbers[::2]) # [0, 2, 4, 6, 8] (every second)

print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse)

Lists Are Mutable (Changing Items)
Unlike strings, lists can be changed after creation. You can modify individual items using index assignment.

Python

fruits = [“apple”, “banana”, “cherry”]

print(fruits) # [‘apple’, ‘banana’, ‘cherry’]

# Change the second item

fruits[1] = “blueberry”

print(fruits) # [‘apple’, ‘blueberry’, ‘cherry’]

# Change a slice (multiple items at once)

fruits[0:2] = [“apricot”, “avocado”]

print(fruits) # [‘apricot’, ‘avocado’, ‘cherry’]

🕯️ Magic Note

Because lists are mutable, they behave differently than strings when passed to functions. Changing a list inside a function changes the original list outside as well. This is called mutability and it is both powerful and dangerous.

Adding Items to a List
Python provides several methods to add items to a list. Each has a different purpose.
MethodWhat It DoesExampleResult
.append(x)Adds x to the end of the list[1,2].append(3)[1, 2, 3]
.insert(i, x)Inserts x at index i (shifts right)[1,3].insert(1,2)[1, 2, 3]
.extend(iter)Adds all items from another iterable[1,2].extend([3,4])[1, 2, 3, 4]
+ operatorCreates a new list (original unchanged)[1,2] + [3,4][1, 2, 3, 4]

Python

shopping = []

# Append adds one item to the end

shopping.append(“milk”)

shopping.append(“eggs”)

print(shopping) # [‘milk’, ‘eggs’]

# Insert at a specific position

shopping.insert(1, “bread”)

print(shopping) # [‘milk’, ‘bread’, ‘eggs’]

# Extend adds multiple items from another list

shopping.extend([“butter”, “cheese”])

print(shopping) # [‘milk’, ‘bread’, ‘eggs’, ‘butter’, ‘cheese’]

💡 Use .append() for adding one item. Use .extend() for combining two lists. Use + when you need to keep the original lists unchanged and create a new list.
Removing Items from a List
Several methods remove items from a list. Choose based on what you know about the item.
MethodWhat It DoesExampleResult
.remove(x)Removes the first occurrence of x (error if not found)[1,2,1].remove(1)[2, 1]
.pop(i)Removes and returns item at index i (default: last)[1,2,3].pop()returns 3, list becomes [1, 2]
.clear()Removes all items from the list[1,2,3].clear()[]
delDeletes item by index or slicedel my_list[0]removes first item

Python

colors = [“red”, “blue”, “green”, “blue”, “yellow”]

# Remove by value (first occurrence only)

colors.remove(“blue”)

print(colors) # [‘red’, ‘green’, ‘blue’, ‘yellow’]

# Pop removes and returns by index

removed = colors.pop(1)

print(removed) # green

print(colors) # [‘red’, ‘blue’, ‘yellow’]

# Pop with no argument removes the last item

last = colors.pop()

print(last) # yellow

print(colors) # [‘red’, ‘blue’]

⚠️ .remove() raises a ValueError if the item does not exist. Always check if the item is in the list first, or use a try-except block.
Finding Items in a List
Use .index() to find the position of an item. Use in to check if an item exists.

Python

fruits = [“apple”, “banana”, “cherry”, “banana”]

# Check existence

print(“banana” in fruits) # True

print(“grape” in fruits) # False

# Find index (first occurrence)

pos = fruits.index(“banana”)

print(pos) # 1

# .index() with start and end parameters

pos = fruits.index(“banana”, 2)

print(pos) # 3 (searches from index 2 onward)

# Count occurrences

print(fruits.count(“banana”)) # 2

💡 Always check with in before calling .index() if you are not sure the item exists. Or use .count() which returns 0 if the item is not found.
List Length and Membership
The len() function works on lists exactly like it works on strings.

Python

items = [“spell”, “potion”, “wand”]

print(len(items)) # 3

# Empty list is False in boolean context

empty = []

if empty:

print(“This won’t print”)

else:

print(“Empty list is falsy”) # This prints

🕯️ Magic Note

An empty list evaluates to False in boolean contexts. This is useful for checking if a list has any items: if my_list: means “if my_list is not empty”.

Looping Through Lists
The for loop is the most common way to iterate over a list.

Python

colors = [“red”, “green”, “blue”]

# Loop through items

for color in colors:

print(color)

# Output:

# red

# green

# blue

# Loop with index using enumerate

for i, color in enumerate(colors):

print(f”{i}: {color}”)

# 0: red

# 1: green

# 2: blue

List Methods: Sort and Reverse
Lists have built-in methods for sorting and reversing. These modify the list in place.

Python

numbers = [3, 1, 4, 1, 5, 9, 2]

# .sort() modifies the list in ascending order

numbers.sort()

print(numbers) # [1, 1, 2, 3, 4, 5, 9]

# .sort(reverse=True) for descending

numbers.sort(reverse=True)

print(numbers) # [9, 5, 4, 3, 2, 1, 1]

# .reverse() reverses the order in place

numbers.reverse()

print(numbers) # [1, 1, 2, 3, 4, 5, 9] (back to original order)

# sorted() returns a new list (original unchanged)

original = [3, 1, 2]

new = sorted(original)

print(original) # [3, 1, 2] (unchanged)

print(new) # [1, 2, 3] (new sorted list)

💡 Use .sort() when you want to modify the original list. Use sorted() when you need to keep the original unchanged. The same applies to reverse: .reverse() vs reversed().
Copying Lists
Assigning a list to another variable does not copy it. Both variables point to the same list. To create a true copy, use slicing or .copy().

Python

original = [1, 2, 3]

# This does NOT create a copy (both reference the same list)

not_a_copy = original

not_a_copy.append(4)

print(original) # [1, 2, 3, 4] (original changed!)

# Three ways to create a true copy

copy1 = original.copy()

copy2 = original[:]

copy3 = list(original)

copy1.append(5)

print(original) # [1, 2, 3, 4] (unchanged)

print(copy1) # [1, 2, 3, 4, 5]

⚠️ For nested lists (lists containing other lists), simple copy methods create a shallow copy. The inner lists are still shared. For deep copies, use import copy; copy.deepcopy(my_list).
Nested Lists
Lists can contain other lists. Access nested items using multiple indices.

Python

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

]

print(matrix[0]) # [1, 2, 3] (first row)

print(matrix[1][2]) # 6 (second row, third column)

# Loop through a nested list

for row in matrix:

for item in row:

print(item, end=” “)

# 1 2 3 4 5 6 7 8 9

Common Mistakes with Lists
  • Accidentally sharing a list instead of copying it: b = a does not copy
  • Modifying a list while iterating over it (causes skipped items or errors)
  • Using .remove() without checking if the item exists
  • Confusing .append() with .extend(): .append([1,2]) adds one nested list, .extend([1,2]) adds two items
  • Forgetting that .sort() returns None (it modifies in place)
  • Using index out of range causing IndexError
Check Your Understanding
  • How do you create a list with the numbers 10, 20, and 30?
  • What is the difference between .append() and .extend()?
  • How do you get the last item of a list without knowing its length?
  • Write code to check if “apple” is in a list called fruits.
  • Why does b = a not create a copy of a list?
  • What is the output of [1,2,3].pop() and what does the list become?

⚡ Whisper

A list is a shelf where you store your treasures. You can reach for the first item, the last, or any in between. You can add new treasures at the end or slip them between existing ones. You can remove what you no longer need. The list holds your items in order, waiting for you to return. But remember: when you hand someone your list, you are not giving them a copy. You are showing them the shelf itself. If they rearrange it, your treasures move too. Be careful what you share. Be mindful of what you change.

Related posts