title: Combining elements in a list in Python where sequence matters
body: <p>I have a 2d list </p>
  
  <pre><code>a = [[[6, 7], [7, 4]],
      [[4, 7], [7, 8], [8, 15]],
      [[3, 19], [15, 3], [19, 12]]]
  </code></pre>
  
  <p>Figures are the node names in a TSP (<code>[6,7]</code> means go from 6 to 7). Each row in <code>a</code> corresponds to a tour in specific day. I need to make another 2d list which sequences are considered: Below is what I need:</p>
  
  <pre><code>FinalTours = [[6,7,4], 
                [4,7,8,15],
                [15,3,19,12]]
  </code></pre>
  
  <p>Any suggestions?
  I tried the code below but it only works for the first day (first row of <code>a</code>)</p>
  
  <pre><code>FinalTours = [[] for i in range(T)]           
  for t in range(T):
      for i in AllTour[t]:
          if t == 0:
              Wakeup = 6
              if i[0] == Wakeup:
                  Tour =[]
                  Tour.append(Wakeup)
                  Tour.append(i[1])
              else:
                  if i[0] == Tour[-1]:
                      Tour.append(i[1])
                      FinalTours[t] = Tour
  
          else:
              Wakeup = Tour[-1] 
              if i[0] == Wakeup:
                  Tour =[]
                  Tour.append(Wakeup)
                  Tour.append(i[1])
              else:
                  if i[0] == Tour[-1]:
                      Tour.append(i[1])
                      FinalTours[t] = Tour
  </code></pre>