Python Lists
Lists are one of the most versatile and commonly used data structures in Python. A list is an ordered, mutable collection that can hold items of different types.
Creating Lists
python
# Empty list
empty = []
empty = list()
# List with values
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True, None]
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# From other iterables
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
nums = list(range(1, 6)) # [1, 2, 3, 4, 5]
# Repeated values
zeros = [0] * 5 # [0, 0, 0, 0, 0]Accessing Elements
python
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Indexing (0-based)
print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[-1]) # elderberry (last element)
print(fruits[-2]) # date
# Slicing [start:stop:step]
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:3]) # ['apple', 'banana', 'cherry']
print(fruits[2:]) # ['cherry', 'date', 'elderberry']
print(fruits[::2]) # ['apple', 'cherry', 'elderberry']
print(fruits[::-1]) # reversed list
# Nested list access
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0]) # [1, 2, 3]
print(matrix[1][2]) # 6Modifying Lists
python
fruits = ["apple", "banana", "cherry"]
# Change an element
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
# Change a range
fruits[1:3] = ["grape", "kiwi", "mango"]
print(fruits) # ['apple', 'grape', 'kiwi', 'mango']Adding Elements
python
fruits = ["apple", "banana"]
# append() - add to end
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
# insert() - add at specific position
fruits.insert(1, "blueberry")
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry']
# extend() - add multiple items
fruits.extend(["date", "elderberry"])
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry']
# Using += operator
fruits += ["fig"]
print(fruits) # [..., 'fig']Removing Elements
python
fruits = ["apple", "banana", "cherry", "banana", "date"]
# remove() - remove first occurrence by value
fruits.remove("banana")
print(fruits) # ['apple', 'cherry', 'banana', 'date']
# pop() - remove by index and return it
last = fruits.pop() # Remove last
print(last) # date
second = fruits.pop(1) # Remove index 1
print(second) # cherry
# del - delete by index or slice
del fruits[0]
print(fruits) # ['banana']
# clear() - remove all elements
fruits.clear()
print(fruits) # []List Methods Reference
| Method | Description | Example |
|---|---|---|
append(x) | Add to end | [1,2].append(3) → [1,2,3] |
insert(i, x) | Add at index | [1,3].insert(1,2) → [1,2,3] |
extend(iter) | Add multiple | [1].extend([2,3]) → [1,2,3] |
remove(x) | Remove first match | [1,2,2].remove(2) → [1,2] |
pop(i) | Remove & return | [1,2,3].pop(1) → returns 2 |
clear() | Remove all | [1,2].clear() → [] |
index(x) | Find index | [1,2,3].index(2) → 1 |
count(x) | Count occurrences | [1,2,2].count(2) → 2 |
sort() | Sort in-place | [3,1,2].sort() → [1,2,3] |
reverse() | Reverse in-place | [1,2,3].reverse() → [3,2,1] |
copy() | Shallow copy | [1,2].copy() → [1,2] |
Sorting Lists
python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# sort() - modifies in place
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# Reverse sort
numbers.sort(reverse=True)
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# sorted() - returns new list (original unchanged)
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original) # [3, 1, 4, 1, 5] (unchanged)
print(sorted_list) # [1, 1, 3, 4, 5]
# Sort with key function
words = ["banana", "apple", "cherry", "date"]
words.sort(key=len)
print(words) # ['date', 'apple', 'banana', 'cherry']
# Sort objects
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda s: s[1], reverse=True)
print(students) # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]List Comprehensions
A concise way to create lists:
python
# Basic: [expression for item in iterable]
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition: [expression for item in iterable if condition]
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# With if-else
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
# Nested comprehension
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# Flatten a nested list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6]
# String processing
words = ["Hello", "World", "Python"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
lengths = {w: len(w) for w in words}
print(lengths) # {'Hello': 5, 'World': 5, 'Python': 6}List Operations
python
# Length
print(len([1, 2, 3])) # 3
# Membership
print(3 in [1, 2, 3]) # True
print(5 not in [1, 2, 3]) # True
# Concatenation
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
# Repetition
print([0] * 3) # [0, 0, 0]
# Min, max, sum
nums = [3, 1, 4, 1, 5]
print(min(nums)) # 1
print(max(nums)) # 5
print(sum(nums)) # 14
# any() and all()
print(any([False, False, True])) # True (at least one True)
print(all([True, True, True])) # True (all True)
print(all([True, False, True])) # FalseCopying Lists
python
original = [1, [2, 3], 4]
# Shallow copy methods (all equivalent)
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
# Shallow copy shares nested objects!
copy1[1][0] = 99
print(original) # [1, [99, 3], 4] - also changed!
# Deep copy for nested structures
import copy
original = [1, [2, 3], 4]
deep = copy.deepcopy(original)
deep[1][0] = 99
print(original) # [1, [2, 3], 4] - unchanged!Practical Example
python
"""
Shopping list manager using list operations.
"""
def display_list(items):
if not items:
print(" (empty)")
return
for i, item in enumerate(items, 1):
print(f" {i}. {item}")
shopping_list = []
# Add items
shopping_list.extend(["Milk", "Bread", "Eggs", "Butter", "Cheese"])
print("Shopping List:")
display_list(shopping_list)
# Remove purchased item
shopping_list.remove("Bread")
print("\nAfter buying Bread:")
display_list(shopping_list)
# Sort alphabetically
shopping_list.sort()
print("\nSorted:")
display_list(shopping_list)
# Check if item is needed
item = "Eggs"
if item in shopping_list:
print(f"\n✓ {item} is on the list")
# Summary
print(f"\nTotal items: {len(shopping_list)}")Summary
- Lists are ordered, mutable collections created with
[]orlist() - Access elements with indexing (0-based) and slicing
- Add:
append(),insert(),extend(); Remove:remove(),pop(),del - List comprehensions provide concise list creation
sort()modifies in-place;sorted()returns a new list- Use
copy.deepcopy()for deep copies of nested lists - Lists support
+(concatenation),*(repetition),in(membership)
Next, we'll learn about Python tuples.