Python List - Complete Notes
What is a List?
A list in Python is a mutable, ordered collection that can hold items of any data type, including mixed
types.
Example:
my_list = [1, "hello", 3.14, True]
Characteristics of List
- Ordered: Items maintain insertion order
- Mutable: Can be changed after creation
- Heterogeneous: Supports different data types
- Indexing: Supports positive and negative index
Creating a List
empty_list = []
num_list = [1, 2, 3]
mixed_list = [1, "Python", 3.14]
nested_list = [[1, 2], [3, 4]]
Accessing Elements
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # 10
print(my_list[-1]) # 50
print(my_list[1:4]) # [20, 30, 40]
List Operations
- len(lst): Get number of items
- lst1 + lst2: Concatenate lists
- lst * 3: Repeat list
- x in lst: Membership test
- for i in lst: Iteration
Modifying Lists
lst.append(100) # Add one item
lst.extend([1, 2, 3]) # Add multiple items
lst.insert(1, "Python") # Insert at index
lst.remove("Python") # Remove first matching value
lst.pop(2) # Remove by index
lst.clear() # Empties the list
Searching and Counting
lst.index(value) # Returns first index of value
lst.count(value) # Number of times value appears
Looping through Lists
for item in lst:
print(item)
for i in range(len(lst)):
print(f"Index {i}: {lst[i]}")
List Comprehension
squares = [x*x for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
Nested Lists
matrix = [[1, 2], [3, 4]]
print(matrix[1][0]) # 3
Sorting Lists
lst.sort()
lst.sort(reverse=True)
sorted_lst = sorted(lst)
lst.sort(key=len)
Copying a List
b = a.copy()
b = a[:]
b = list(a)
Deleting Items
del lst[0]
del lst[1:3]
del lst
Built-in Functions
len(lst), max(lst), min(lst), sum(lst), sorted(lst), list(iter), enumerate(), zip()
Advanced Concepts
List vs Tuple
List: Mutable, [ ]
Tuple: Immutable, ( )
Shallow vs Deep Copy
import copy
shallow = copy.copy(original)
deep = copy.deepcopy(original)
Unpacking Lists
a, b, c = [1, 2, 3]
*a, last = [1, 2, 3, 4]
Common Errors
- IndexError: Accessing invalid index
- ValueError: Removing a non-existent item
- TypeError: Applying incompatible operations
Best Practices
- Use list comprehension
- Prefer 'in' for membership
- Avoid modifying while iterating
- Use .copy() to avoid linking
Example:
data = [10, 20, 30, 40]
data.append(50)
data.insert(2, 25)
print("Index of 30:", data.index(30))
data.remove(25)
squares = [x*x for x in data if x % 2 == 0]
print("Final List:", data)
print("Squares:", squares)