# Checking for a sequence in a python list

• A+
Category：Languages

I have a list [T20, T5, T10, T1, T2, T8, T16, T17, T9, T4, T12, T13, T18]

I have stripped out the T's, coverted to integer type and sorted the list to get this:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]

I'm looping over the list and checking if the next number to current number is in numerical sequence. If not I want to insert a "V" in its position.

So eventually the list should look like: [1, 2, V, 4, 5, V, V, 8, 9, 10, V, 12, 13, V, V, 16, 17, 18, V, 20]

However, I'm not able to insert the exact no of V's at the right positions.

``def arrange_tickets(tickets_list):      ids=[]     for item in tickets_list:         new_str=item.strip("T")         ids.append(int(new_str))     sorted_ids = sorted(ids)     temp_ids = []     print("Sorted: ",sorted_ids)     #size = len(sorted_ids)     for i in range(len(sorted_ids)-1):         temp_ids.append(sorted_ids[i])          if sorted_ids[i]+1 != sorted_ids[i+1] :             temp_ids.insert(i+1,"V")     print(temp_ids)     #print(sorted_ids)   tickets_list = ['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18'] print("Ticket ids of all the available students :") print(tickets_list) result=arrange_tickets(tickets_list) ``

Actual Result: [1, 2, 'V', 4, 'V', 5, 8, 'V', 9, 'V', 10, 12, 'V', 13, 16, 17, 18]

Expected Result: [T1, T2, V, T4, T5, V, V, T8, T9, T10, V, T12, T13, V, V, T16, T17, T18, V, T20]

Here is a list comprehension which gets you what you want:

``sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20] a = sorted_ids[0] b = sorted_ids[-1] nums = set(sorted_ids) expected = ["T" + str(i) if i in nums else 'V' for i in range(a,b+1)] print(expected) ``

Output:

``['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20'] ``