![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements