# Order the sub-lists in a nested list

## Question:

I have a series of lists, and I want to combine them in a larger nested list. However, I want to order them in a certain way. I want the first sub-list to be the one whose first element is zero. Then i want the second sub-list to be the one whose first element is the same as the LAST element of the previous list.

For example, here’s four sub-lists;

`[0, 3], [7, 0], [3, 8], [8, 7]`

I want to end up with this;

`[[0, 3], [3, 8], [8, 7], [7,0]]`

I can’t for the life of me see the code logic in my head that would achieve this for me.

UPDATE
Solved!
Many thanks to all who contributed!

You can try something like this:

``````source = [[0, 3], [7, 0], [3, 8], [8, 7]]

# Start at 0
last_val = 0
# this will be the output
l = []
while len(l)==0 or last_val!=0:
# Find the first value where the first element is last_val
l.append(next(i for i in source if i[0]==last_val))
# set last val to the second element of the list
last_val = l[-1][1]

print(l)

``````

I think of your list as being a collection of links which are to be arranged into a chain. Here is an approach which uses @quanrama ‘s idea of a dictionary keyed by the first element of that link:

``````links = [[0, 3], [7, 0], [3, 8], [8, 7]]

chain = []
i = min(d)
while d:
del d[i]

print(chain) #[[0, 3], [3, 8], [8, 7], [7, 0]]
``````

Another approach with a generator function:

``````links = [[0, 3], [7, 0], [3, 8], [8, 7]]

key = start
while True: