Python | Arrange Tuples consecutively in list

Sometimes, while working with tuple list, we may require a case in which we require that a tuple starts from the end of previous tuple, i.e the element 0 of every tuple should be equal to ending element of tuple in list of tuple. This type of problem and sorting is useful in competitive programming. Let’s discuss way in which this problem can be solved.

Method : Using loop + dict()
This task can easily be solved by converting a tuple container list to dictionary and then it’s easy to access a value of a key and arrange them accordingly to sort in a way in which one tuple element begins with the ending of other element.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Arranging Tuples consecutively in list
# using loop + dict()
  
# initialize list
test_list = [(5, 6), (11, 8), (6, 11), (8, 9) ]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Arranging Tuples consecutively in list
# using loop + dict()
temp = dict(test_list)  
ele = test_list[0][0]  
res = [] 
for _ in range(len(test_list)):
    res.append((ele, temp[ele]))
    ele = temp[ele]
  
# printing result
print("The arranged list is : " + str(res))

chevron_right


Output :

The original list is : [(5, 6), (11, 8), (6, 11), (8, 9)]
The arranged list is : [(5, 6), (6, 11), (11, 8), (8, 9)]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.