Lists
Lists are mutable, ordered sequences. They can hold items of any type and are one of Python's most versatile data structures.
Creating Lists
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
nested = [[1, 2], [3, 4]]
from_range = list(range(5)) # [0, 1, 2, 3, 4]
Accessing Elements
nums = [10, 20, 30, 40, 50]
nums[0] # 10 — first element
nums[-1] # 50 — last element
nums[1:3] # [20, 30] — slice
nums[:3] # [10, 20, 30] — from start
nums[2:] # [30, 40, 50] — to end
nums[::2] # [10, 30, 50] — every 2nd
nums[::-1] # [50, 40, 30, 20, 10] — reversed
Python Playground
Output
Click "Run" to execute your codeAdding Elements
| Method | Description | Example |
|---|---|---|
append(x) |
Add to end | [1,2].append(3) → [1,2,3] |
insert(i, x) |
Insert at index | [1,3].insert(1, 2) → [1,2,3] |
extend(iter) |
Add all from iterable | [1,2].extend([3,4]) → [1,2,3,4] |
+ |
Concatenate (new list) | [1,2] + [3,4] → [1,2,3,4] |
Removing Elements
| Method | Description | Example |
|---|---|---|
remove(x) |
Remove first occurrence | [1,2,3,2].remove(2) → [1,3,2] |
pop() |
Remove & return last | [1,2,3].pop() → 3 |
pop(i) |
Remove & return at index | [1,2,3].pop(0) → 1 |
clear() |
Remove all elements | [1,2,3].clear() → [] |
del lst[i] |
Delete at index | del lst[0] |
Python Playground
Output
Click "Run" to execute your codeSearching and Counting
| Method | Description |
|---|---|
index(x) |
Index of first x (raises ValueError if not found) |
count(x) |
Number of occurrences of x |
x in lst |
True if x is in list |
Sorting and Reversing
nums = [3, 1, 4, 1, 5, 9]
# In-place sort
nums.sort() # [1, 1, 3, 4, 5, 9]
nums.sort(reverse=True) # [9, 5, 4, 3, 1, 1]
# New sorted list
sorted(nums) # returns new list
sorted(nums, key=abs) # sort by absolute value
# Reverse in place
nums.reverse()
# New reversed
list(reversed(nums))
List Comprehensions
A concise way to create lists:
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# With transformation
words = ["hello", "world"]
upper = [w.upper() for w in words]
# Nested
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
Python Playground
Output
Click "Run" to execute your codeUseful Built-in Functions
| Function | Description | Example |
|---|---|---|
len(lst) |
Number of elements | len([1,2,3]) → 3 |
sum(lst) |
Sum of elements | sum([1,2,3]) → 6 |
min(lst) |
Smallest element | min([3,1,2]) → 1 |
max(lst) |
Largest element | max([3,1,2]) → 3 |
any(lst) |
True if any truthy |
any([0, False, 1]) → True |
all(lst) |
True if all truthy |
all([1, True, "a"]) → True |
enumerate(lst) |
Index-value pairs | list(enumerate(["a","b"])) → [(0,"a"),(1,"b")] |
zip(a, b) |
Pair elements | list(zip([1,2], ["a","b"])) → [(1,"a"),(2,"b")] |
Copying Lists
original = [1, 2, 3]
# Shallow copies
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
# Deep copy (for nested lists)
import copy
deep = copy.deepcopy(original)