Python – Adjacent elements in List


When it is required to display adjacent elements in list, a method is defined that uses enumerate and a simple iteration to determine the result.

Example

Below is a demonstration of the same −

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))

Output

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)]

Explanation

  • A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list.

  • An empty list is created.

  • The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined.

  • If index value is 0, the element in first index is appended to the empty list.

  • If index is equal to length of list minus 1, the element in previous index is appended to empty list.

  • Otherwise, both the previous and next elements are appended to the empty list.

  • Outside the method, a list is defined and displayed on the console.

  • The method is called by passing the required parameter.

  • The output is displayed on the console.

Updated on: 08-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements