Python – Extend consecutive tuples



When it is required to extend consecutive tuples, a simple iteration is used.

Example

Below is a demonstration of the same −

my_list = [(13, 526, 73), (23, 67, 0, 72, 24, 13), (94, 42), (11, 62, 23, 12), (93, ), (83, 61)] print("The list is :") print(my_list) my_list.sort(reverse=True) print("The list after sorting in reverse is :") print(my_list) my_result = [] for index in range(len(my_list) - 1): my_result.append(my_list[index] + my_list[index + 1]) print("The result is :") print(my_result)

Output

The list is : [(13, 526, 73), (23, 67, 0, 72, 24, 13), (94, 42), (11, 62, 23, 12), (93,), (83, 61)] The list after sorting in reverse is : [(94, 42), (93,), (83, 61), (23, 67, 0, 72, 24, 13), (13, 526, 73), (11, 62, 23, 12)] The result is : [(94, 42, 93), (93, 83, 61), (83, 61, 23, 67, 0, 72, 24, 13), (23, 67, 0, 72, 24, 13, 13, 526, 73), (13, 526, 73, 11, 62, 23, 12)]

Explanation

  • A list of tuples is defined and is displayed on the console.

  • It is sorted in reverse using ‘sorted’ method and displayed on the console.

  • An empty list is created.

  • The list is iterated over, consecutive elements are added and appended to the empty list.

  • This is the output that is displayed on the console.

Updated on: 2021-09-13T07:24:47+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements