Python lists - creation, indexing, and common methods
list creation, indexing, negative indexing, slicing, append, extend, remove, pop, len, list mutability
Python Lists
A list is an ordered, mutable sequence. It can hold items of mixed types, though keeping types consistent is good practice.
nums = [10, 20, 30, 40, 50]
print(nums[0]) # 10 - first element
print(nums[-1]) # 50 - last element
print(nums[1:4]) # [20, 30, 40] - slice
Common Methods
fruits = ["apple", "banana"]
fruits.append("cherry") # add to end
fruits.extend(["date", "fig"]) # merge another list
fruits.insert(1, "avocado") # insert at index
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return last
print(len(fruits)) # current length
print(fruits.index("apple")) # 0
print(fruits.count("apple")) # 1
Mutability
Lists are mutable - you can change elements in place. Assigning a list to another variable does not copy it; both names point to the same object. Use list.copy() or list[:] to create a shallow copy when you need independence.
a = [1, 2, 3]
b = a # b is a reference, not a copy
b.append(4)
print(a) # [1, 2, 3, 4] - a was modified too
c = a.copy() # independent copy
Lists are one of the most frequently used data structures in Python. Slicing with [start:stop:step] is a powerful pattern - lst[::-1] reverses a list in one line. Sorting is done with list.sort() (in-place) or sorted(list) (returns a new list). When iterating a list while modifying it, iterate over a copy or use list comprehensions to build a new list - modifying a list in place during iteration causes skipped elements and is a frequent source of bugs.
