List Basics
Overview
Lists in Python are dynamic arrays. They are ordered, extremely flexible, and mutable (meaning you can change their contents after creation). Unlike arrays in C or Java which have fixed sizes and enforce single data types, Python lists can grow or shrink dynamically and can store an arbitrary mix of strings, integers, floats, or even other lists. They are the absolute foundation of data storage in Python and the starting point for nearly all algorithmic challenges.
Syntax
# Creating lists
numbers = [10, 20, 30, 40]
mixed_data = ["Alice", 25, True, 3.14]
# Accessing elements (O(1) time complexity)
print(numbers[0]) # 10 (First element)
print(numbers[-1]) # 40 (Last element)
# Modifying elements in-place
numbers[1] = 99
print(numbers) # [10, 99, 30, 40]
# Getting the length of a list
print(len(numbers)) # 4Common Pitfalls
- Accessing out of bounds indices. Asking for
numbers[10]in a 4-element list throws an immediate IndexError. - Assigning lists like
list_b = list_a. This does NOT duplicate the list. Both variables now point to the exact same memory location. Changinglist_bwill inherently changelist_a.
Interview Questions
O(1) Constant Time. Under the hood, Python lists are dynamic arrays of memory pointers. The interpreter can instantly calculate exactly where any given index resides in memory.
Real-World Example
Duplicating a list properly using slicing to avoid reference mutation.
original_prices = [10, 20, 30]
# Creating a shallow copy using [:]
discounted_prices = original_prices[:]
# Modifying the copy does not affect the original
discounted_prices[0] = 5
print(original_prices) # [10, 20, 30]
print(discounted_prices) # [5, 20, 30]Check Your Knowledge
Test your understanding of List Basics with these quick questions.