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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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 06:48:21