Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Adjacent elements in List
When working with lists in Python, you often need to find adjacent elements for each item. This involves getting the previous and next elements relative to each position in the list.
Understanding Adjacent Elements
Adjacent elements are the neighboring items in a list:
- For the first element, only the next element exists
- For the last element, only the previous element exists
- For middle elements, both previous and next elements exist
Using enumerate() to Find Adjacent Elements
The enumerate() function provides both index and value, making it easy to access neighboring elements ?
def find_adjacent_elements(my_list):
my_result = []
for index, ele in enumerate(my_list):
if index == 0:
my_result.append((None, my_list[index + 1]))
elif index == len(my_list) - 1:
my_result.append((my_list[index - 1], None))
else:
my_result.append((my_list[index - 1], my_list[index + 1]))
return my_result
my_list = [13, 37, 58, 12, 41, 25, 48, 19, 23]
print("The list is:")
print(my_list)
print("The result is:")
print(find_adjacent_elements(my_list))
The output of the above code is ?
The list is: [13, 37, 58, 12, 41, 25, 48, 19, 23] The result is: [(None, 37), (13, 58), (37, 12), (58, 41), (12, 25), (41, 48), (25, 19), (48, 23), (19, None)]
How It Works
The function iterates through the list using enumerate() to get both index and element:
-
First element (index 0): Returns
(None, next_element) -
Last element: Returns
(previous_element, None) -
Middle elements: Returns
(previous_element, next_element)
Alternative Approach Using List Comprehension
You can achieve the same result with a more concise list comprehension ?
def find_adjacent_compact(my_list):
return [(my_list[i-1] if i > 0 else None,
my_list[i+1] if i < len(my_list)-1 else None)
for i in range(len(my_list))]
my_list = [13, 37, 58, 12, 41]
print("Original list:", my_list)
print("Adjacent elements:", find_adjacent_compact(my_list))
The output of the above code is ?
Original list: [13, 37, 58, 12, 41] Adjacent elements: [(None, 37), (13, 58), (37, 12), (58, 41), (12, None)]
Conclusion
Finding adjacent elements is useful for sliding window operations and neighbor analysis. Use enumerate() for readable code or list comprehension for compact solutions.
