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>In python, one tends not to use the actual indexes in a list very often. Try a for-loop instead, plus a check to see whether the trend changed or not (this treats zero as a distinct trend from positive or negative - you can pretty simply change <code>same_direction</code> to group it one way or the other):</p>

<pre><code>def same_direction(num1, num2):
    # both numbers are positive, both are negative, or both are zero
    return ((num1 &gt; 0 and num2 &gt; 0) or
            (num1 &lt; 0 and num2 &lt; 0) or
            (num1 == num2))

numbers = [1, 2, -1, -2, 4, 5]
result = [[]] #list with one sublist ready
last_number = 0
for num in numbers:
    if same_direction(num, last_direction):
        # No need for a new sublist, put new number in last sublist
        result[-1].append(num)
    else:
        # trend changed, new sublist and put the number in it
        result.append([num])
</code></pre>

python list python-2.7 trend