Method: Using yield + loop + generator
A crude method to execute, — this is to use a generator and keep printing the value if we know the elements are bound to form a loop, and this is done in an infinite loop and stops when no more matches are found.
# Python3 code to demonstrate how it works # Join a loop in the list # Using yield + loop + generator # helper function for this task def cycle (test_list, val, stop = None ): temp = dict (test_list) stop = stop if stop is not None else val while True : yield (val) val = temp.get (val, stop) if val = = st op: break # initializing list test_list = [ [ 6 , 7 ], [ 9 , 6 ], [ 7 , 9 ]] # print of the original list print ( "The original list is: " + str (test_list)) # Join the loop in the list # Using yield + loop + generator # print result print ( " The cycle elements are: " ) for ele in cycle (test_list, 6 ): print (ele) |
Output:
The original list is: [[6, 7], [9, 6], [7, 9]] The cycle elements are: 6 7 9