Learn how to use Python lists of lists with clear syntax, beginner-friendly examples, and practical real-world applications. Perfect for data organization and manipulation!
#
A list of lists in Python is exactly what it sounds like - a list that contains other lists as its elements. This is a fundamental concept in Python thatβs incredibly useful for organizing and manipulating structured data.
list_of_lists = [
[item1, item2, item3], # First inner list
[item4, item5, item6], # Second inner list
# ... and so on
]
# A 2D list representing a matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# A list of student records
students = [
["Alice", 22, "Computer Science"],
["Bob", 21, "Mathematics"],
["Charlie", 23, "Physics"]
]
print(matrix[0]) # Output: [1, 2, 3]
print(matrix[1][2]) # Output: 6 (second row, third column)
print(students[2][0]) # Output: "Charlie"
matrix[0][1] = 99 # Change the second element of first row
students.append(["Diana", 20, "Biology"]) # Add a new student
# Print each row of the matrix
for row in matrix:
print(row)
# Print student names and majors
for name, age, major in students:
print(f"{name} studies {major}")
# Sales data: [product, quantity, price]
sales = [
["Laptop", 5, 999.99],
["Phone", 12, 699.99],
["Tablet", 8, 349.99]
]
# Tic-tac-toe board
board = [
["X", "O", " "],
[" ", "X", " "],
["O", " ", "X"]
]
# Simple grayscale image (2x3 pixels)
image = [
[120, 200, 150], # First row of pixels
[30, 180, 220] # Second row of pixels
]
# Graph where nodes are connected to other nodes
graph = [
[1, 2], # Node 0 is connected to nodes 1 and 2
[0, 3], # Node 1 is connected to nodes 0 and 3
[0, 3, 4], # Node 2 is connected to nodes 0, 3, and 4
[1, 2], # Node 3 is connected to nodes 1 and 2
[2] # Node 4 is connected to node 2
]
# Survey responses: each inner list is one respondent's answers
survey_responses = [
[1, 5, 2, 4], # Respondent 1
[3, 3, 2, 5], # Respondent 2
[5, 1, 4, 2] # Respondent 3
]
matrix[0][0]
is the first element of the first list.Lists of lists are a simple yet powerful way to organize data in Python, and understanding them will help you work with more complex data structures later on.
Tutorials, Roadmaps, Bootcamps & Visualization Projects