Consecutive elements pairing in list in Python

PythonServer Side ProgrammingProgramming

During data analysis using python, we may come across a need to pair-up the consecutive elements of a list. In this article we will see the various ways to achieve this.

With index and range

We will design an expression to put the consecutive indexes of the list elements together. And then apply the range function to determine the maximum number of times this pairing of consecutive elements will go on.

Example

 Live Demo

listA = [51,23,11,45]
# Given list
print("Given list A: ", listA)
# Use
res = [[listA[i], listA[i + 1]]
   for i in range(len(listA) - 1)]
# Result
print("The list with paired elements: \n",res)

Output

Running the above code gives us the following result −

Given list A: [51, 23, 11, 45]
The list with paired elements:
[[51, 23], [23, 11], [11, 45]]

With map and zip

We can also take help of map and zip functions and slicing. We slice the element at position 1 and combine it with elements at position 0. We repeat this for each pair of elements using the zip and map functions.

Example

 Live Demo

listA = [51,23,11,45]
# Given list
print("Given list A: ", listA)
# Use zip
res = list(map(list, zip(listA, listA[1:])))
# Result
print("The list with paired elements: \n",res)

Output

Running the above code gives us the following result −

Given list A: [51, 23, 11, 45]
The list with paired elements:
[[51, 23], [23, 11], [11, 45]]
raja
Published on 20-May-2020 14:02:42
Advertisements