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
# Python3 code to demonstrate working of
# Adjacent elements in List
# Using loop
# Function to find adjacent
# elements in List
def findAdjacentElements(test_list):
res = []
for idx, ele in enumerate(test_list):
# Checking for all cases to append
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
# Initializing list
input_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# Printing original list
print("The original list is:", input_list)
# printing result
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
# Initializing the list
test_list = [3, 7, 9, 3]
# Printing the input
print("The original input is: ",test_list)
# List comprehension
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))]
# Printing the result
print("The result is: ",result)
OutputThe 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
# Initializing the list
test_list = [3, 7, 9, 3]
# Printing the input
print("The original input is:", test_list)
# Using zip() function and list slicing
result = list(zip(test_list[:-2], test_list[2:]))
# Handling the first and last elements
result.insert(0, (None, test_list[1]))
result.append((test_list[-2], None))
# Printing the result
print("The result is:", result)
OutputThe 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.
Similar Reads
Python | Consecutive elements pairing in list This process involves creating pairs of elements that appear next to each other, which can be invaluable for various applications such as data analysis, pattern recognition and algorithm development. We can achieve this using different methods in Python, such as using simple loops, list slicing, zip
3 min read
Python - Non K distant elements Given a list, the task is to write a Python program to extract all the elements such that no element is at K distant from one other. Examples: Input : test_list = [8, 10, 16, 20, 3, 1, 7], K = 2 Output : [16, 20, 7] Explanation : 16 + 2 = 18, 16 - 2 = 14, both are not in list, hence filtered. Input
2 min read
Get first and last elements of a list in Python The task of getting the first and last elements of a list in Python involves retrieving the initial and final values from a given list. For example, given a list [1, 5, 6, 7, 4], the first element is 1 and the last element is 4, resulting in [1, 4]. Using indexingThis is the most straightforward way
3 min read
Python - Adjacent Coordinates in N dimension Sometimes, while working with Python Matrix, we can have a problem in which we need to extract all the adjacent coordinates of the given coordinate. This kind of problem can have application in many domains such as web development and school programming. Lets discuss certain way in which this task c
3 min read
Python - Add List Items Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples:Add a Single Item Using append()append() method adds one item to the end of the li
3 min read