Skip to content
Related Articles

Related Articles

Python | Pair iteration in list

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 14 Sep, 2022
View Discussion
Improve Article
Save Article

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

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!