Python – Adjacent elements in List
Last Updated :
24 May, 2023
Given a List extract both next and previous element for each element.
Input : test_list = [3, 7, 9, 3]
Output : [(None, 7), (3, 9), (7, 3), (9, None)]
Explanation : for 7 left element is 3 and right, 9.
Input : test_list = [3, 7, 3]
Output : [(None, 7), (3, 3), (7, None)]
Explanation : for 7 left element is 3 and right, 3.
Method 1: Using loop
In this, we iterate for each element and get next and previous element using element access.
Python3
def findAdjacentElements(test_list):
res = []
for idx, ele in enumerate (test_list):
if idx = = 0 :
res.append(( None , test_list[idx + 1 ]))
elif idx = = len (test_list) - 1 :
res.append((test_list[idx - 1 ], None ))
else :
res.append((test_list[idx - 1 ], test_list[idx + 1 ]))
return res
input_list = [ 3 , 7 , 8 , 2 , 1 , 5 , 8 , 9 , 3 ]
print ( "The original list is:" , input_list)
print ( "The Adjacent elements list:" , findAdjacentElements(input_list))
|
Output:
The original list is: [3, 7, 8, 2, 1, 5, 8, 9, 3] The Adjacent elements list: [(None, 7), (3, 8), (7, 2), (8, 1), (2, 5), (1, 8), (5, 9), (8, 3), (9, None)]
Method 2: Using List comprehension
In this approach, we use list comprehension to generate a list of tuples that contain the adjacent elements. The list comprehension iterates over the indices of the test_list, and for each index i, we get the left adjacent element with test_list[i-1] if i > 0, and None otherwise. Similarly, we get the right adjacent element with test_list[i+1] if i < len(test_list)-1, and None otherwise. We then create a tuple of the left and right adjacent elements and append it to the result list for each iteration.
Finally, we print the result list to the console, which contains the desired output.
Python3
test_list = [ 3 , 7 , 9 , 3 ]
print ( "The original input is: " ,test_list)
result = [(test_list[i - 1 ] if i > 0 else None , test_list[i + 1 ] if i < len (test_list) - 1 else None ) for i in range ( len (test_list))]
print ( "The result is: " ,result)
|
Output
The original input is: [3, 7, 9, 3]
The result is: [(None, 7), (3, 9), (7, 3), (9, None)]
Time Complexity: O(n)
Auxiliary Space: O(logn)
Method 3: Use the zip() function along with list slicing.
Python3
test_list = [ 3 , 7 , 9 , 3 ]
print ( "The original input is:" , test_list)
result = list ( zip (test_list[: - 2 ], test_list[ 2 :]))
result.insert( 0 , ( None , test_list[ 1 ]))
result.append((test_list[ - 2 ], None ))
print ( "The result is:" , result)
|
Output
The original input is: [3, 7, 9, 3]
The result is: [(None, 7), (3, 9), (7, 3), (9, None)]
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list.
Share your thoughts in the comments
Please Login to comment...