Web Analytics

Lists

Beginner ~25 min read

Lists are Python's most versatile data structure - ordered, mutable collections that can hold any type of data. Think of a list like a dynamic container that can grow, shrink, and change its contents at any time. If you're coming from other languages, lists are similar to arrays but much more powerful!

Creating Lists

Lists are created using square brackets [] with items separated by commas. Python lists can hold any data type - numbers, strings, booleans, even other lists!

Output
Click Run to execute your code
List Characteristics: Lists in Python are (1) Ordered - items maintain their insertion order, (2) Mutable - you can change, add, and remove items, (3) Allow duplicates - the same value can appear multiple times, and (4) Heterogeneous - can mix different data types in one list.

Accessing Elements with Indexing

Every item in a list has a position called an index. Python uses zero-based indexing - the first element is at index 0, the second at index 1, and so on. You can also use negative indices to count from the end!

Output
Click Run to execute your code
Pro Tip: Use negative indexing when you need elements from the end of a list. my_list[-1] always gives you the last element, regardless of list length - much cleaner than my_list[len(my_list)-1]!

Extracting Sublists with Slicing

Slicing lets you extract a portion of a list using the syntax list[start:end:step]. It creates a new list containing elements from start up to (but not including) end, optionally skipping by step.

Output
Click Run to execute your code
Slicing Creates a Copy! When you slice a list, Python creates a new list. The original list remains unchanged. This is important to remember for memory usage with large lists. my_list[:] is a common idiom to create a shallow copy of a list.

Modifying Lists

Unlike strings and tuples, lists are mutable - you can change their contents after creation. You can modify individual elements, replace entire sections, add new elements, or remove existing ones.

Output
Click Run to execute your code

Common Mistakes

1. IndexError - Accessing invalid index

# Wrong - index out of range
fruits = ["apple", "banana", "cherry"]
print(fruits[3])  # IndexError! Valid indices: 0, 1, 2

# Correct - check length first or use try/except
if len(fruits) > 3:
    print(fruits[3])
else:
    print("Index out of range")

2. Confusing index and value

# Wrong - remove() takes value, not index
numbers = [10, 20, 30]
numbers.remove(1)  # Tries to remove VALUE 1, not index 1!

# Correct
numbers.remove(20)  # Remove by value
# OR
numbers.pop(1)      # Remove by index

3. Off-by-one in slicing

# Wrong assumption - end index is exclusive!
numbers = [0, 1, 2, 3, 4]
first_three = numbers[0:2]  # Only gets [0, 1], not [0, 1, 2]

# Correct - remember end is exclusive
first_three = numbers[0:3]  # Gets [0, 1, 2]
# Or more simply:
first_three = numbers[:3]

4. Forgetting that assignment creates references

# Wrong - both variables point to same list!
original = [1, 2, 3]
copy = original  # This is NOT a copy!
copy.append(4)
print(original)  # [1, 2, 3, 4] - original changed too!

# Correct - create actual copy
copy = original[:]      # Slice copy
copy = original.copy()  # copy() method
copy = list(original)   # list() constructor

Exercise: Shopping List Manager

Task: Create and manipulate a shopping list.

Requirements:

  • Create a list with "milk", "eggs", "bread"
  • Print the second item (eggs)
  • Change "bread" to "whole wheat bread"
  • Add "butter" to the end of the list
  • Print the final list
Output
Click Run to execute your code
Show Solution
# Create the shopping list
shopping_list = ["milk", "eggs", "bread"]

# Print second item (index 1)
print(shopping_list[1])  # eggs

# Change bread to whole wheat bread (index 2)
shopping_list[2] = "whole wheat bread"

# Add butter to end
shopping_list.append("butter")

print(f"Final Shopping List: {shopping_list}")
# Output: ['milk', 'eggs', 'whole wheat bread', 'butter']

Summary

  • Creating: Use [] with comma-separated values
  • Properties: Ordered, mutable, allow duplicates, heterogeneous
  • Positive index: list[0] = first, list[1] = second
  • Negative index: list[-1] = last, list[-2] = second to last
  • Slicing: list[start:end:step] - end is exclusive!
  • Modifying: list[i] = value, append(), insert(), remove(), pop()
  • Copy: Use list[:] or .copy(), not =

What's Next?

Now that you understand how to create and access lists, let's explore the powerful built-in List Methods that let you sort, search, count, and transform your lists with ease!