Python List of Lists: Syntax, Examples & Real-World Use Cases for Beginners
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.
Basic Syntax
list_of_lists = [ [item1, item2, item3], # First inner list [item4, item5, item6], # Second inner list # ... and so on]
Simple Examples
Example 1: Creating a list of lists
# A 2D list representing a matrixmatrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]# A list of student recordsstudents = [ ["Alice", 22, "Computer Science"], ["Bob", 21, "Mathematics"], ["Charlie", 23, "Physics"]]
matrix[0][1] = 99 # Change the second element of first rowstudents.append(["Diana", 20, "Biology"]) # Add a new student
Example 4: Iterating through a list of lists
# Print each row of the matrixfor row in matrix: print(row)# Print student names and majorsfor name, age, major in students: print(f"{name} studies {major}")
Real-World Use Cases
Tabular Data Representation: Before using pandas or other data science libraries, lists of lists are often used to represent spreadsheet-like data.
Image Processing: Representing pixel data (before using specialized libraries).
# Simple grayscale image (2x3 pixels)image = [ [120, 200, 150], # First row of pixels [30, 180, 220] # Second row of pixels]
Graph Representation: Adjacency lists for graph data structures.
# Graph where nodes are connected to other nodesgraph = [ [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 or Questionnaire Data: Storing responses to multiple questions.
# Survey responses: each inner list is one respondent's answerssurvey_responses = [ [1, 5, 2, 4], # Respondent 1 [3, 3, 2, 5], # Respondent 2 [5, 1, 4, 2] # Respondent 3]
Tips for Beginners
Remember that indexing starts at 0: matrix[0][0] is the first element of the first list.
You can have lists of different lengths within your main list.
Lists are mutable - you can change their contents after creation.
For more complex operations, consider using list comprehensions or libraries like NumPy for numerical data.
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.