Working with Lists
Working with Lists
Lists are ordered, mutable collections that can hold any type of data.
Creating Lists
# Empty list
empty = []
# List with values
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
# Using list() constructor
letters = list("hello") # ['h', 'e', 'l', 'l', 'o']
Accessing Elements
fruits = ["apple", "banana", "cherry", "date"]
# Positive indexing (from start)
print(fruits[0]) # "apple"
print(fruits[1]) # "banana"
# Negative indexing (from end)
print(fruits[-1]) # "date"
print(fruits[-2]) # "cherry"
Slicing
Get a portion of a list:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:3]) # [0, 1, 2]
print(numbers[7:]) # [7, 8, 9]
print(numbers[::2]) # [0, 2, 4, 6, 8] (every 2nd)
print(numbers[::-1]) # [9, 8, 7, ...] (reversed)
Modifying Lists
fruits = ["apple", "banana", "cherry"]
# Change an element
fruits[1] = "blueberry"
print(fruits) # ["apple", "blueberry", "cherry"]
# Add to end
fruits.append("date")
print(fruits) # ["apple", "blueberry", "cherry", "date"]
# Insert at position
fruits.insert(1, "apricot")
print(fruits) # ["apple", "apricot", "blueberry", "cherry", "date"]
# Remove by value
fruits.remove("cherry")
# Remove by index
del fruits[0]
# or
popped = fruits.pop(0) # Returns the removed item
List Methods
| Method | Description | Example |
|---|---|---|
append(x) |
Add item to end | lst.append(4) |
insert(i, x) |
Insert at index | lst.insert(0, "first") |
remove(x) |
Remove first occurrence | lst.remove("apple") |
pop(i) |
Remove and return item | lst.pop() or lst.pop(0) |
clear() |
Remove all items | lst.clear() |
index(x) |
Find index of item | lst.index("apple") |
count(x) |
Count occurrences | lst.count(5) |
sort() |
Sort in place | lst.sort() |
reverse() |
Reverse in place | lst.reverse() |
copy() |
Create a copy | new = lst.copy() |
List Comprehensions
A concise way to create lists:
# Traditional way
squares = []
for x in range(5):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Common Operations
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Length
print(len(numbers)) # 8
# Sum
print(sum(numbers)) # 31
# Min/Max
print(min(numbers)) # 1
print(max(numbers)) # 9
# Check membership
print(5 in numbers) # True
print(7 in numbers) # False
# Concatenation
a = [1, 2]
b = [3, 4]
c = a + b # [1, 2, 3, 4]
Practice
Try solving the Two Sum problem after this lesson - it's a classic list manipulation challenge!