In Python, a list is a way to store a bunch of things (items) in a specific order. It's like your to-do list, your shopping list, or a list of your favorite games. Lists are super flexible and can hold almost anything!
What's a List?
Think of it like a to-do list! Lists have these key characteristics:
- Lists are ordered: The order you put things in matters.
- Lists are mutable: You can change them after creation (add, remove, change items).
- Lists can contain different data types: Mix numbers, strings, and even other lists!
Creating Lists
Empty List
Create a list with no initial items
my_list = []
print(my_list) # Output: []List with Initial Values
Create a list with starting values
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
Tip: Lists are created using square brackets
[] with items separated by commas.
Accessing List Items (Indexing)
Each item has a position called an index. The first item is index 0, second is 1, etc.
Positive Indexing
Access items from the start of the list
my_list = ["apple", "banana", "cherry"]
first = my_list[0] # "apple"
second = my_list[1] # "banana"
third = my_list[2] # "cherry"Negative Indexing
Access items from the end of the list
my_list = ["apple", "banana", "cherry"]
last = my_list[-1] # "cherry"
second_last = my_list[-2] # "banana"
Warning: Accessing an invalid index (e.g.,
my_list[10] on a 3-item list) causes an IndexError.
List Slicing
Get a part of a list (sublist) using slicing.
Basic Slicing
Get items from start to end (end not included)
my_list = ["a", "b", "c", "d", "e"]
sub1 = my_list[1:4] # ["b", "c", "d"]
sub2 = my_list[:3] # ["a", "b", "c"]
sub3 = my_list[2:] # ["c", "d", "e"]
full = my_list[:] # Copy of entire listStep Slicing
Skip elements using step parameter
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = numbers[::2] # [0, 2, 4, 6, 8]
odds = numbers[1::2] # [1, 3, 5, 7, 9]
reverse = numbers[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Tip: Slicing syntax is
list[start:end:step]. Omit start for beginning, omit end for end of list.
Modifying Lists
Adding Items
Different ways to add items to lists
fruits = ["apple", "banana"]
# Add to end
fruits.append("orange") # ["apple", "banana", "orange"]
# Insert at position
fruits.insert(1, "grape") # ["apple", "grape", "banana", "orange"]
# Add multiple items
fruits.extend(["kiwi", "mango"]) # Adds both to endRemoving Items
Different ways to remove items from lists
fruits = ["apple", "banana", "cherry", "banana"]
# Remove by value (first occurrence)
fruits.remove("banana") # ["apple", "cherry", "banana"]
# Remove by index and return value
last = fruits.pop() # "banana", fruits = ["apple", "cherry"]
first = fruits.pop(0) # "apple", fruits = ["cherry"]
# Delete by index (no return)
del fruits[0] # fruits = []
# Clear entire list
fruits.clear() # fruits = []Changing Items
Modify existing items
fruits = ["apple", "banana", "cherry"]
fruits[0] = "grapefruit" # ["grapefruit", "banana", "cherry"]
fruits[-1] = "blueberry" # ["grapefruit", "banana", "blueberry"]List Length & Looping
Finding Length
Get the number of items in a list
my_list = ["apple", "banana", "cherry"]
length = len(my_list) # 3Looping Through Lists
Process each item in a list
fruits = ["apple", "banana", "cherry"]
# Method 1: Direct iteration
for fruit in fruits:
print(f"I like {fruit}")
# Method 2: Using indices
for i in range(len(fruits)):
print(f"Fruit {i}: {fruits[i]}")
# Method 3: With enumerate (best practice)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")Essential List Methods
sort() & reverse()
Sort or reverse list order
numbers = [3, 1, 4, 1, 5]
numbers.sort() # [1, 1, 3, 4, 5]
numbers.reverse() # [5, 4, 3, 1, 1]
# Sort without modifying original
sorted_nums = sorted(numbers)count() & index()
Find occurrences and positions
numbers = [1, 2, 2, 3, 2, 4]
count = numbers.count(2) # 3
position = numbers.index(3) # 3 (index of first occurrence)
# Safe index checking
if 5 in numbers:
pos = numbers.index(5)copy() & clear()
Copy or empty a list
original = [1, 2, 3]
copy1 = original.copy() # Shallow copy
copy2 = original[:] # Another way to copy
original.clear() # []Advanced Techniques
List Comprehensions
Concise way to create new lists
numbers = [1, 2, 3, 4, 5]
# Squares of numbers
squares = [x**2 for x in numbers] # [1, 4, 9, 16, 25]
# Even numbers only
evens = [x for x in numbers if x % 2 == 0] # [2, 4]
# With condition and transformation
processed = [x*2 if x % 2 == 0 else x for x in numbers]
# [1, 4, 3, 8, 5]Nested Lists
Lists containing other lists
# 2D grid (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Access elements
print(matrix[0][1]) # 2 (first row, second column)
# Flatten a nested list
flat = [item for row in matrix for item in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]Lists vs. Other Types
Lists vs. Strings
Key differences between lists and strings
# Strings are IMMUTABLE
my_string = "hello"
# my_string[0] = "j" # ERROR!
# Lists are MUTABLE
my_list = ["h", "e", "l", "l", "o"]
my_list[0] = "j" # Works! ["j", "e", "l", "l", "o"]
# Both support indexing and slicing
print(my_string[1:4]) # "ell"
print(my_list[1:4]) # ["e", "l", "l"]Lists vs. Tuples
When to use lists vs tuples
# Lists: mutable, use for collections that change
shopping_list = ["milk", "eggs", "bread"]
shopping_list.append("cheese") # OK
# Tuples: immutable, use for fixed collections
point = (3, 4) # Coordinates
rgb = (255, 128, 0) # Color values
# Convert between them
list_from_tuple = list(point) # [3, 4]
tuple_from_list = tuple(shopping_list) # ("milk", "eggs", ...)Practice Challenges
- Create a list of your 5 favorite songs.
- Add a new song to the end of the list.
- Remove the second song from the list.
- Print the list of songs, one song per line.
- Create a new list that contains only songs starting with "B" (use list comprehension!)
- Advanced: Create a nested list representing a 3x3 tic-tac-toe board and write functions to check for wins.
- Pro: Implement a function that removes duplicates from a list while preserving order.
Remember: The best way to learn is by doing! Try modifying these examples and creating your own list challenges.