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, list elements are accessed using indexing and the difference is found.

Example

Below is a demonstration of the same

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

print("The list is :")
print(my_list)
my_indices_list = [idx for idx in range(
   len(my_list)) if my_list[idx] % 2 == 0]

my_result = my_indices_list[-1] - my_indices_list[0]

print("The result is :")
print(my_result)

Output

The list is :
[2, 3, 6, 4, 6, 2, 9, 1, 14, 11]
The result is :
8

Explanation

  • A list is defined and is displayed on the console.

  • The list is iterated over, and the elements are checked to see if divisible by 2.

  • If so, they are assigned to a variable.

  • The difference between last and first element is obtained by indexing them.

  • This difference is assigned to a variable.

  • This variable is displayed on the console.

Updated on: 20-Sep-2021

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements