Open In App

Python | Pair iteration in list

Improve
Improve
Like Article
Like
Save
Share
Report

List iteration is common in Python programming, but sometimes one requires to print the elements in consecutive pairs. This particular problem is quite common and having a solution to it always turns out to be handy. Let’s discuss certain ways in which this problem can be solved. 

Pair iteration in a list using list comprehension 

List comprehension can be used to print the pairs by accessing the current and next elements in the list and then printing the same. Care has to be taken while pairing the last element with the first one to form a cyclic pair. 

Python3




from itertools import compress
 
# initializing list
test_list = [0, 1, 2, 3, 4, 5]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using list comprehension
# to perform pair iteration in list
res = [((i), (i + 1) % len(test_list))
        for i in range(len(test_list))]
 
# printing result
print ("The pair list is : " + str(res))


Output:

The original list is : [0, 1, 2, 3, 4, 5]
The pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]

Time complexity: O(n), where n is the length of the test_list. 
Auxiliary space: O(n), where n is the length of the test_list.

Pair iteration in a list using zip() + list slicing 

The zip function can be used to extract pairs over the list slicing can be used to successively pair the current element with the next one for efficient pairing. 

Python3




from itertools import compress
 
# initializing list
test_list = [0, 1, 2, 3, 4, 5]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using zip() + list slicing
# to perform pair iteration in list
res = list(zip(test_list, test_list[1:] + test_list[:1]))
 
# printing result
print ("The pair list is : " + str(res))


Output:

The original list is : [0, 1, 2, 3, 4, 5]
The pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list. 

Pair iteration in a list using lambda and itertools:

One approach to iterating over pairs in a list using a lambda function could be as follows:

Python3




from itertools import tee
 
def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)
 
test_list = [0, 1, 2, 3, 4, 5]
 
result = list(map(lambda x: (x[0], x[1]), pairwise(test_list)))
print(result)
#This code is contributed by Edula Vinay Kumar Reddy


Output

[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

Time complexity: O(n) as it requires a single pass through the iterable to create the pairs.
Auxiliary space: O(n) as it requires storing the pairs in a list.

Pair iteration in a list using  a for loop:

Python3




test_list = [0, 1, 2, 3, 4, 5]
# printing original list
print ("The original list is : " + str(test_list))
res = []
for i in range(len(test_list)):
    res.append((test_list[i], test_list[(i + 1) % len(test_list)]))
print("The pair list is :", res)
#This code is contributed by Jyothi pinjala.


Output

The original list is : [0, 1, 2, 3, 4, 5]
The pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach#5: Using zip

This approach creates pairs of adjacent elements in a list by using the zip function to combine each element with its neighbor, and adding the first element to the end to form a circular list. The resulting pairs are returned as a list of tuples.

Algorithm

1. Create a list comprehension to generate the pair list using a for loop and zip function
2. Append a tuple containing e and its next element
3. Return the pair list

Python3




def pair_iteration(lst):
    pairs = [(e1, e2) for e1, e2 in zip(lst, lst[1:]+[lst[0]])]
    return pairs
lst = [0, 1, 2, 3, 4, 5]
print(pair_iteration(lst))


Output

[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]

Time Complexity: O(n)
Space Complexity: O(n)

Approach#6: Using reduce:

Algorithm:

  1. Initialize the input list test_list.
  2. Print the original list.
     
  3. Use reduce() method to iterate over pairs of elements in the input list using a lambda function.
  4. The lambda function takes two arguments x and y, where x is the accumulated list of pairs so far and y is the current element in the list.
  5. Append a new pair (y, x[-1][0]) to the accumulated list x, where the first element is the current element y and the second element is the first element of the last pair in x.
  6. Use test_list[1:] as the initial value for reduce() to skip the first element of the input list, and use [(test_list[0], test_list[-1])] as the initial value for x to create a pair of the first and last elements of the input list.
  7. Print the resulting pair list.

Python3




from functools import reduce
 
# initializing list
test_list = [0, 1, 2, 3, 4, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using reduce() to perform pair iteration
res = reduce(lambda x, y: x + [(y, x[-1][0])], test_list[1:], [(test_list[0], test_list[-1])])
 
# printing result
print("The pair list is : " + str(res))
#This code is contrinuted by Pushpa.


Output

The original list is : [0, 1, 2, 3, 4, 5]
The pair list is : [(0, 5), (1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]

Time Complexity:  O(N) where N is the length of the input list. The reduce() function iterates over each element in the input list.

Space Complexity:  O(N) where N is the length of the input list. The accumulated list x created by the reduce() function can be as large as the input list.



Last Updated : 15 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads