Python – Elements with same index

When working with lists, sometimes you need to find elements whose values match their index positions. Python provides several approaches to accomplish this task using iteration and the enumerate() function.

Using enumerate() with Loop

The most straightforward approach uses enumerate() to get both index and element, then compares them ?

numbers = [33, 1, 2, 45, 41, 13, 6, 9]

print("The list is:")
print(numbers)

result = []
for index, element in enumerate(numbers):
    if index == element:
        result.append(element)

print("Elements matching their index:")
print(result)
The list is:
[33, 1, 2, 45, 41, 13, 6, 9]
Elements matching their index:
[1, 2, 6]

Using List Comprehension

A more concise approach using list comprehension ?

numbers = [33, 1, 2, 45, 41, 13, 6, 9]

result = [element for index, element in enumerate(numbers) if index == element]

print("Original list:", numbers)
print("Elements matching their index:", result)
Original list: [33, 1, 2, 45, 41, 13, 6, 9]
Elements matching their index: [1, 2, 6]

How It Works

The enumerate() function returns pairs of (index, element) for each item in the list:

  • Index 0 has element 33 (0 ? 33, not included)

  • Index 1 has element 1 (1 = 1, included)

  • Index 2 has element 2 (2 = 2, included)

  • Index 6 has element 6 (6 = 6, included)

Practical Example

Finding elements that match their position in a data validation scenario ?

data = [0, 1, 5, 3, 4, 8, 6, 7, 10]

matching_elements = []
for i, value in enumerate(data):
    if i == value:
        matching_elements.append((i, value))
        print(f"Match found: index {i}, value {value}")

print(f"\nTotal matches: {len(matching_elements)}")
Match found: index 0, value 0
Match found: index 1, value 1
Match found: index 3, value 3
Match found: index 4, value 4
Match found: index 6, value 6
Match found: index 7, value 7

Total matches: 6

Conclusion

Use enumerate() with a loop for readable code when you need additional processing. Use list comprehension for concise one-liners when you only need the filtered results.

Updated on: 2026-03-26T01:02:28+05:30

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements