Iterative Pair Pattern in Python

Hey there my fellow python developers, today we are going to learn about iterative Pair Pattern in Python programming.

Well, iterative pairs could be understood as the making pairs of the current and the next element of a list.

Now, let us see how this works:

 

Methods Implemented to form iterative pairs in Python:

Iterative pairs over a list can be formed in the following methods:

  • Iterating over the list taking two elements at a time.
  • Using the zip function with list slicing.

Now, let us see how this works:

 

Iterating over the list taking two elements at a time:

In this method, we iterate over the list in such a way that we take two elements at a time ie the present element and the next element keeping in mind to connect the last element with the first element.

 

a = [2,5,1,5,7,3,4,6,3] 
print ("The Given list is : " + str(a)) 
pair_list=[]
for i in range(len(a)-1):
    pair_list.append((a[i], a[i + 1]))
print ("The Pair-Wise list is : " + str(pair_list))

This gives us the output:

 

Using the zip function with list slicing:

In this method, we use the slicing method on the given list to get the present and the next element.

Then we use the zip function to zip them together.

 

a = [2,5,1,5,7,3,4,6,3] 
print ("The Given list is : " + str(a)) 
pair_list=[]

for previous, current in zip(a, a[1:]):
    pair_list.append((previous, current))
print ("The Pair-Wise list is : " + str(pair_list))    

This gives us the output:

 

And there you have it, “Iterative Pair Pattern in Python”.

I hope you enjoyed the read.

Thanx for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *