Introduction
Lists are ordered, mutable collections that can hold items of different types.
Creating and Accessing
fruits = ["apple", "banana", "cherry", "date"]
numbers = [1, 2, 3, 4, 5]
# Accessing
print(fruits[0]) # apple
print(fruits[-1]) # date
# Slicing
print(numbers[1:4]) # [2, 3, 4]
List Methods
nums = [3, 1, 4, 1, 5]
nums.append(9) # Add to end
nums.insert(0, 0) # Insert at index
nums.remove(1) # Remove first occurrence
nums.pop() # Remove and return last
nums.sort() # Sort in place
nums.reverse() # Reverse in place
nums.extend([7, 8]) # Add multiple elements
List Comprehensions
# Traditional
squares = []
for i in range(10):
squares.append(i ** 2)
# List comprehension
squares = [i ** 2 for i in range(10)]
# With condition
evens = [i for i in range(20) if i % 2 == 0]
Practice Problems
- Find second largest element in list
- Remove duplicates while preserving order
- Flatten nested lists
- Find intersection of two lists
- Implement stack using list