Python | Consecutive elements pairing in list
Sometimes, while working with lists, we need to pair up the like elements in list and then store them as lists of list. This particular task has its utility in many domains, be it web development or day-day programming. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list comprehension
The list comprehension can be easily used to perform this particular task, but consecutively making the pairs of i’th and (i+1)th element.
# Python3 code to demonstrate # consecutive element pairing # using list comprehension # initializing list test_list = [5, 4, 1, 3, 2] # printing original list print("The original list : " + str(test_list)) # using list comprehension # consecutive element pairing res = [[test_list[i], test_list[i + 1]] for i in range(len(test_list) - 1)] # print result print("The consecutive element paired list is : " + str(res)) |
The original list : [5, 4, 1, 3, 2] The consecutive element paired list is : [[5, 4], [4, 1], [1, 3], [3, 2]]
Method #2 : Using zip() + map()
This task can also be achieved using the zip function which performs the task for all the elements and map function does the task of pairing of consecutive elements.
# Python3 code to demonstrate # consecutive element pairing # using zip() + map() # initializing list test_list = [5, 4, 1, 3, 2] # printing original list print("The original list : " + str(test_list)) # using zip() + map() # consecutive element pairing res = list(map(list, zip(test_list, test_list[1:]))) # print result print("The consecutive element paired list is : " + str(res)) |
The original list : [5, 4, 1, 3, 2] The consecutive element paired list is : [[5, 4], [4, 1], [1, 3], [3, 2]]
Recommended Posts:
- Python | Consecutive remaining elements in list
- Python | Consecutive elements grouping in list
- Python | Group consecutive list elements with tolerance
- Python | Consecutive duplicates all elements deletion in list
- Python | Check if list contains consecutive numbers
- Python | Identical Consecutive Grouping in list
- Python | Consecutive Maximum Occurrence in list
- Python | Remove consecutive duplicates from list
- Python | Average of each n-length consecutive segment in a list
- Python | Replace elements in second list with index of same element in first list
- Python | Add list elements with a multi-list based on index
- Python | Sorting list of lists with similar list elements
- Python | Merge List with common elements in a List of Lists
- Python | Indices of sorted list of list elements
- Python | Maximum sum of elements of list in a list of lists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



