How to iterate through a nested List in Python?

A nested list in Python is a list that contains other lists as elements. Iterating through nested lists requires different approaches depending on the structure and your specific needs.

What is a Nested List?

Here are common examples of nested lists ?

# List with mixed data types
people = [["Alice", 25, ["New York", "NY"]], 
          ["Bob", 30, ["Los Angeles", "CA"]], 
          ["Carol", 28, ["Chicago", "IL"]]]

# 3-dimensional nested list
matrix = [
    [['a', 'b'], ['c', 'd']],
    [['e', 'f'], ['g', 'h']]
]

print("People data:", people)
print("Matrix:", matrix)
People data: [['Alice', 25, ['New York', 'NY']], ['Bob', 30, ['Los Angeles', 'CA']], ['Carol', 28, ['Chicago', 'IL']]]
Matrix: [[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]

Method 1: Using Index Access

Access specific elements using their index positions ?

people = [["Alice", 25, ["New York", "NY"]], 
          ["Bob", 30, ["Los Angeles", "CA"]], 
          ["Carol", 28, ["Chicago", "IL"]]]

print("Iterating using index access:")
for person in people:
    name = person[0]
    age = person[1]
    city = person[2][0]
    state = person[2][1]
    print(f"{name} is {age} years old and lives in {city}, {state}")
Iterating using index access:
Alice is 25 years old and lives in New York, NY
Bob is 30 years old and lives in Los Angeles, CA
Carol is 28 years old and lives in Chicago, IL

Method 2: Using isinstance() for Dynamic Checking

Check if an element is a list before iterating through it ?

people = [["Alice", 25, ["New York", "NY"]], 
          ["Bob", 30, ["Los Angeles", "CA"]]]

print("Using isinstance() to check for nested lists:")
for person in people:
    print(f"\nProcessing record:")
    for item in person:
        if isinstance(item, list):
            print(f"  Location: {', '.join(item)}")
        else:
            print(f"  Data: {item}")
Using isinstance() to check for nested lists:

Processing record:
  Data: Alice
  Data: 25
  Location: New York, NY

Processing record:
  Data: Bob
  Data: 30
  Location: Los Angeles, CA

Method 3: Using Nested Loops for Multi-dimensional Lists

Use multiple nested loops for deeply nested structures ?

matrix = [
    [['a', 'b'], ['c', 'd']],
    [['e', 'f'], ['g', 'h']]
]

print("3D matrix elements:")
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        for k in range(len(matrix[i][j])):
            print(f"matrix[{i}][{j}][{k}] = {matrix[i][j][k]}")
3D matrix elements:
matrix[0][0][0] = a
matrix[0][0][1] = b
matrix[0][1][0] = c
matrix[0][1][1] = d
matrix[1][0][0] = e
matrix[1][0][1] = f
matrix[1][1][0] = g
matrix[1][1][1] = h

Method 4: Using Recursive Approach

For arbitrarily nested lists, recursion provides a clean solution ?

def flatten_nested_list(nested_list):
    """Recursively flatten a nested list"""
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten_nested_list(item))
        else:
            result.append(item)
    return result

# Test with various nesting levels
mixed_nested = [1, [2, 3], [4, [5, 6]], 7]
flattened = flatten_nested_list(mixed_nested)

print("Original:", mixed_nested)
print("Flattened:", flattened)
Original: [1, [2, 3], [4, [5, 6]], 7]
Flattened: [1, 2, 3, 4, 5, 6, 7]

Comparison of Methods

Method Best For Complexity Flexibility
Index Access Known structure Simple Low
isinstance() Mixed data types Medium Medium
Nested Loops Fixed dimensions Medium Medium
Recursion Unknown depth Complex High

Conclusion

Choose index access for simple, known structures. Use isinstance() for mixed data types, nested loops for fixed dimensions, and recursion for arbitrarily deep nesting. Each method serves different use cases in handling nested lists effectively.

Updated on: 2026-03-27T06:11:11+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements