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>Here is my solution:</p>

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

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


forward = 1

for i in range(0, len(numbers) - 1):
    if ( forward == 1 ):
        if numbers[i] &lt;= numbers[i+1]:
            subset.append(numbers[i+1])
        else:
            subset_list.append(subset)
            subset = []
            subset.append(numbers[i+1])
            forward = 0
    else:
        if numbers[i] &gt;= numbers[i+1]:
            subset.append(numbers[i+1])
        else:
            subset_list.append(subset)
            subset = []
            subset.append(numbers[i+1])
            forward = 1

subset_list.append(subset)

print(*subset)          
print(*subset_list)
</code></pre>

<p>Unfortunately, I only have python 3 on my system so my answer is in python 3.</p>

python list python-2.7 trend