A List is the most versatile way to store a collection of items. While they are similar to arrays in C, Python lists are much more powerful because they can hold different types of data (integers, strings, even other lists) and can change size dynamically.
1. Key Characteristics
Ordered: They maintain the order in which items are inserted.
Mutable: You can add, remove, or change items after the list is created.
Indexed: The first item is at index
0, just like in C.
2. Common List Operations
Python provides built-in methods to manage your data without manually shifting elements in memory.
Method Action
append(x)Adds an item to the end of the list.
insert(i, x)Adds an item at a specific index.
remove(x)Removes the first occurrence of a specific value.
pop()Removes and returns the last item.
sort()Sorts the list in ascending order.
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(f"First fruit: {fruits[0]}") # apple
# Adding and Modifying
fruits.append("orange") # Adds to end
fruits[1] = "blackberry" # Replaces 'banana'
# Removing
fruits.pop(2) # Removes 'cherry' (index 2)
# Iterating through a list (very common!)
print("\nMy Fruit List:")
for fruit in fruits:
print(f"- {fruit}")
# List Slicing (Getting a sub-portion)
numbers = [0, 10, 20, 30, 40, 50]
print(f"Middle slice: {numbers[2:5]}") # Indices 2, 3, and 4 -> [20, 30, 40]