Python Lists 📜
What is a List?
Lists are used to store multiple items in a single variable. They are one of 4 built-in data types in Python used to store collections of data. Lists are ordered, changeable, and allow duplicate values.
🛒 Analogy: The Shopping List
A Python list is like a real-world shopping list.
- You can add items to the bottom (append).
- You can cross items off (remove).
- The order matters (ordered).
- You can have "Milk" written twice (duplicates allowed).
✨ Creating and Accessing
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry" (Negative Indexing)
print(fruits[1:3]) # ["banana", "cherry"] (Slicing)🛠️ Modifying Lists
Lists are mutable, meaning you can change their content.
fruits = ["apple", "banana", "cherry"]
# Change Item
fruits[1] = "blackcurrant"
# Add Item
fruits.append("orange")
# Insert at Index
fruits.insert(1, "blueberry")
# Remove Item
fruits.remove("apple")
print(fruits)🔧 Under the Hood: Dynamic Arrays
How Lists Grow
Python lists are implemented as dynamic arrays. When you create a list, Python allocates a block of memory.
When you append() and the block is full, Python automatically:
1. Allocates a larger block of memory (usually 1.125x or 2x larger).
2. Copies all items to the new block.
3. Deletes the old block.
This makes append() usually very fast (O(1)), but occasionally slow when a resize happens.
🚀 List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
The Old Way
fruits = ["apple", "banana", "cherry"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)The Pythonic Way
fruits = ["apple", "banana", "cherry"]
newlist = [x for x in fruits if "a" in x]
print(newlist)⚠️ Copying Lists
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy() # Correct way to copy⚠️ Watch Out: Nested Lists
.copy() only creates a shallow copy. If your list contains other lists, the inner lists are still shared!
For a full independent copy, use import copy; copy.deepcopy(list).
💡 Did You Know?
Lists can contain different data types, and even other lists (nested lists):
list1 = ["abc", 34, True, ["nested", "list"]]