Filtering a list. Get elements of list only with a certain distance between items?
<p>I need to get only those elements that are to some extent distant from each other. For example, I have a list of integers:</p>

<pre><code>data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]
</code></pre>

<p>Let's assume I want to retrieve only those elements that have have a distance of at least <strong>1000</strong> between each other.
From the list above I need output:</p>

<pre><code>[-2000, 1000, 2000, 3500, 4500, 6000]
</code></pre>

<hr>

<p>For the moment I'm filtering this way:</p>

<pre><code>filtered.append(data[0])
for index, obj in enumerate(data):
    if index &lt; (l - 1): 
        if abs(obj - data[index+1]) &gt; 999:
            filtered.append(data[index+1])

print(filtered)
</code></pre>

<p>Undesired output:</p>

<pre><code>[-2000, 1000, 2000, 3500, 6000]
</code></pre>

<hr>

<p>It fails because it compares two adjacent list elements, irregardless of the fact that some elements supposed to be filtered out and should not be taken into account when comparing. </p>

<p>Let me show more clearly.<br>
Original list: <code>[-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]</code></p>

<p>Filtering process: </p>

<pre><code>-2000 - OK
1000 - OK
2000 - OK
3500 - OK
3800 - Out
4500 - Should be OK, but it filtered out compared to 3800. But it should be compared to 3500 (not 3800 which is Out). 
</code></pre>

<hr>

<p>How to fix it?</p>

<p>Sorting the data and then comparing to the previous would do it:</p>

<pre><code>data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]

lst = [min(data)]          # the min of data goes in solution list
for i in sorted(data[1:]):
  if i-lst[-1] &gt; 999:      # comparing with last element
    lst.append(i)          # of the solution list

print (lst)
</code></pre>

<p>ouput:</p>

<pre><code>[-2000, 1000, 2000, 3500, 4500, 6000]
</code></pre>

python list python-3.x distance