How to find consecutive/successive objects in a list of objects
<p>I have a list of object that have attributes serial number (SN) and datetime along with others. From how the list is generated, the objects should be in chronological order.
Cronologically, objects can have the following SN:</p>

<p>1,1,1,1,1,2,2,2,3,3,3,3,3,3,2,2,1,2,2,2,2,3,3,1,1,1,3,...</p>

<p>How can I retrive the first an last timestamps of all consecutive sequences of SN. For example for SN=1 that would be the first to fith timestamp as well as the 17th and 24th to 26th.
Same for all SNs that appear in the list of objects.
What I want to go for is a Gantt like Diagram to show at which times these SNs were present.</p>

<p>If I understand your question correctly, maybe you are looking for something like this?</p>

<pre><code>def consecutive(nums, sn):
    count = {nums[0]: [[0]]}
    for idx, num in enumerate(nums[1:]):
        if num == nums[idx]:
            try:
                count[num][-1][1] = idx + 1
            except IndexError:
                count[num][-1].append(idx + 1)
        else:
            try:
                count[nums[idx]][-1][1] = idx + 1
            except IndexError:
                count[nums[idx]][-1].append(idx + 1)
            try:
                count[num].append([idx + 1])
            except KeyError:
                count[num] = [[idx + 1]]
    return count[sn]
</code></pre>

<p>test:</p>

<pre><code>test = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 1, 2, 2, 2, 2, 3, 3, 1, 1, 1, 3]
print consecutive(test, 3) # will return [[8, 14], [21, 23], [26]], which are the index ranges for SN = 3
</code></pre>

python