Python – Find the distance between first and last even elements in a List

When it is required to find the distance between the first and last even elements of a list, we can use list comprehension to find indices of even numbers and calculate the difference between the first and last positions.

Example

Below is a demonstration of finding the distance between first and last even elements ?

my_list = [2, 3, 6, 4, 6, 2, 9, 1, 14, 11]

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

# Find indices of all even elements
my_indices_list = [idx for idx in range(len(my_list)) if my_list[idx] % 2 == 0]

# Calculate distance between first and last even element
my_result = my_indices_list[-1] - my_indices_list[0]

print("The result is :")
print(my_result)
The list is :
[2, 3, 6, 4, 6, 2, 9, 1, 14, 11]
The result is :
8

How It Works

  • A list is defined and displayed on the console

  • List comprehension iterates over indices and checks if elements are divisible by 2

  • Even element indices are stored in my_indices_list

  • The distance is calculated by subtracting the first index from the last index

  • The result represents the number of positions between first and last even elements

Alternative Approach

We can also find the first and last even positions directly without storing all indices ?

my_list = [2, 3, 6, 4, 6, 2, 9, 1, 14, 11]

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

# Find first even element position
first_even_pos = None
for idx, num in enumerate(my_list):
    if num % 2 == 0:
        first_even_pos = idx
        break

# Find last even element position
last_even_pos = None
for idx in range(len(my_list) - 1, -1, -1):
    if my_list[idx] % 2 == 0:
        last_even_pos = idx
        break

distance = last_even_pos - first_even_pos
print("The distance is :")
print(distance)
The list is :
[2, 3, 6, 4, 6, 2, 9, 1, 14, 11]
The distance is :
8

Conclusion

Use list comprehension for a concise solution when the list is small. Use the iterative approach for better memory efficiency with large lists containing many even numbers.

Updated on: 2026-03-26T02:39:54+05:30

503 Views

Advertisements