Lecture 1: Lists in Python

1. List Initialization

Lists are ordered, mutable collections that can store elements of different data types.

# Empty list empty_list = [] # List with elements numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] # Using list() constructor chars = list("Python") print(chars) # Output: ['P', 'y', 't', 'h', 'o', 'n']

2. List Methods

Lists have several built-in methods for manipulation.

Method Description Example
append(x) Adds an item to the end nums.append(6)
insert(i, x) Inserts item at index nums.insert(0, 0)
remove(x) Removes first occurrence nums.remove(3)
pop([i]) Removes and returns item at index last = nums.pop()
sort() Sorts the list in place nums.sort()
reverse() Reverses the list in place nums.reverse()
index(x) Returns index of first occurrence idx = nums.index(4)
count(x) Counts occurrences of x cnt = nums.count(2)

3. List Operations

Common operations on lists.

# Concatenation list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 # [1, 2, 3, 4, 5, 6] # Repetition repeated = [0] * 5 # [0, 0, 0, 0, 0] # Membership exists = 3 in list1 # True # Length length = len(list1) # 3

4. Indexing and Slicing

numbers = [10, 20, 30, 40, 50] # Indexing (0-based) first = numbers[0] # 10 last = numbers[-1] # 50 # Slicing [start:stop:step] first_three = numbers[0:3] # [10, 20, 30] even_indices = numbers[::2] # [10, 30, 50] reversed_list = numbers[::-1] # [50, 40, 30, 20, 10] # Modifying with slices numbers[1:3] = [25, 35] # [10, 25, 35, 40, 50]

5. List Comprehension

Concise way to create lists.

# Squares of numbers squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16] # Even numbers evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8] # Nested list comprehension matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9]

6. Nesting in Lists

Lists can contain other lists, creating multi-dimensional structures.

# 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Accessing elements value = matrix[1][2] # 6 (row 1, column 2) # Iterating through 2D list for row in matrix: for item in row: print(item, end=' ') print() # New line after each row # List of mixed data types mixed_list = [ [1, 2, 3], "hello", {'name': 'John', 'age': 30}, (4, 5, 6) ]