Python - Print rows from the matrix that have same element at a given index

When working with matrices (lists of lists), you may need to filter rows where all elements have the same digit at a specific position. This can be achieved using list comprehension with the all() function to check if elements share a common digit at a given index position.

Problem Statement

Given a matrix and an index position, find all rows where every element has the same digit at that specific index position when converted to string.

Example

Let's find rows where all elements have the same digit at index position 1 ?

matrix = [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]

print("The matrix is:")
print(matrix)

index_key = 1
print("The index position is:", index_key)

# Find rows where all elements have same digit at given index
result = [row for row in matrix if all(str(element)[index_key] == str(row[0])[index_key] for element in row)]

print("Rows with same digit at index", index_key, ":")
print(result)
The matrix is:
[[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]
The index position is: 1
Rows with same digit at index 1 :
[[7745, 6755, 87, 978], [192, 997, 49]]

How It Works

The solution uses list comprehension with the all() function:

  • Convert to strings: str(element) converts each number to string to access individual digits
  • Extract digit: str(element)[index_key] gets the digit at the specified position
  • Compare with first element: Each element's digit is compared with the first element's digit at the same position
  • Check all elements: all() ensures every element in the row satisfies the condition

Step-by-Step Analysis

Let's trace through the example to understand better ?

matrix = [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]
index_key = 1

print("Analyzing each row:")
for i, row in enumerate(matrix):
    digits_at_index = [str(element)[index_key] for element in row]
    print(f"Row {i}: {row}")
    print(f"Digits at index {index_key}: {digits_at_index}")
    
    # Check if all digits are the same
    first_digit = digits_at_index[0]
    all_same = all(digit == first_digit for digit in digits_at_index)
    print(f"All same? {all_same}")
    print()
Analyzing each row:
Row 0: [7745, 6755, 87, 978]
Digits at index 1: ['7', '7', '7', '7']
All same? True

Row 1: [727, 927, 845]
Digits at index 1: ['2', '2', '4']
All same? False

Row 2: [192, 997, 49]
Digits at index 1: ['9', '9', '9']
All same? True

Row 3: [98, 74, 27]
Digits at index 1: ['8', '4', '7']
All same? False

Alternative Approach Using Function

Here's a more readable approach using a helper function ?

def filter_rows_by_digit_index(matrix, index_pos):
    """Filter rows where all elements have same digit at given index position"""
    result = []
    
    for row in matrix:
        # Get digits at the specified index for all elements in row
        digits = [str(element)[index_pos] for element in row]
        
        # Check if all digits are the same
        if len(set(digits)) == 1:  # Set with 1 element means all are same
            result.append(row)
    
    return result

# Test the function
matrix = [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]
filtered_rows = filter_rows_by_digit_index(matrix, 1)

print("Original matrix:", matrix)
print("Filtered rows:", filtered_rows)
Original matrix: [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]
Filtered rows: [[7745, 6755, 87, 978], [192, 997, 49]]

Conclusion

Use list comprehension with all() to filter matrix rows based on digit patterns. Convert numbers to strings to access individual digit positions, and compare all elements against the first element's digit at the specified index.

Updated on: 2026-03-26T00:56:53+05:30

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements