Subsetting python list into positive/negative movements/trends
<p>Sorry for creating this question but I have been stuck on this question for a while.</p>

<p>Basically I'm trying to take a list:</p>

<pre><code>numbers=[1, 2, -1, -2, 4, 5]
</code></pre>

<p>And subset this list into a list of list that display positive/negative movements (or trends)</p>

<p>The end result is to have:</p>

<pre><code>subset_list = [[1, 2], [-1, -2], [4, 5]] 
</code></pre>

<p>Basically I have been using nested while functions to append a positive movement to the subset, and when the condition is not met, the subset is appended to subset_list and then evaluates if there is a negative movement.</p>

<p>I keep getting an <code>IndexError</code>, and so far <code>subset_list</code> only contains <code>[[1, 2]]</code></p>

<p>Here is my code:</p>

<pre><code>numbers = [1,2,-1,-2,4,5]

subset = []
subset_list = []
subset.append(numbers[0])

i = 1
while i &lt; (len(numbers)):
    if numbers[i] &lt;= numbers[i+1]:
        subset.append(numbers[i])
        i+= 1
        while subset[-1] &lt;= numbers[i] or numbers[i] &lt;= numbers[i+1]:
            subset.append(numbers[i])
            i += 1
        subset_list.append(subset)
        subset = []
        i += 1
    if numbers[i] &gt; numbers[i+1]:
        subset.append(numbers[i])
        i+= 1
        while subset[-1] &lt;= numbers[i] or numbers[i] &lt;= numbers[i+1]:
            subset.append(numbers[i])
            i+= 1
        subset_list.append(subset)
        subset = []
        i += 1
</code></pre>

<p>Thanks!</p>

<p>-Jake</p>

<p>This is what I came up with. It is close to what you have but a little easier to read. I avoid having to increment the index counter <code>i</code> as much which is <em>probably</em> where you went wrong.</p>

<pre><code>n= [1,2,-1,-2,4,5]
out=[]
i=1
tmp=[n[0]]
while i &lt; len(n):
        if n[i] &gt;= 0 and tmp[-1] &gt;= 0:
                tmp.append(n[i])
        elif n[i] &lt; 0 and tmp[-1] &lt; 0:
                tmp.append(n[i])
        else:
                out.append(tmp)
                tmp = [n[i]]
        i = i + 1
if len(tmp) &gt; 0: # typo fix was &gt; 1
        out.append(tmp)

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

python list python-2.7 trend