Python: how to create sublists through loop?
<p>I have a long list containing elements that value from 0 to 100.
What I want to do is find all the positions where my elements take on values [0,2]. Then find out all the positions of the values between 2 and 4, etc up to 98 and 100.</p>

<p>Let's call the list containing the values ''list''. And let's call the resulting list p_x. Where x indicates which interval we are finding the positions of.</p>

<p>I managed to get what i want this way:
p_61 = N.where((list >= 60) &amp; (list &lt;= 62))  </p>

<p>My question now is: how do i loop this, so that i get as a result all the p_x's that I want?</p>

<pre><code>import itertools

l = list(range(10))

## If you just want the values:
print([(x,y) for (x,y) in itertools.combinations(l, 2) if abs(x-y)==2])

## If you want the positions:
for i, x in enumerate(l):
    for j, y in enumerate(l):
        if j &lt;= i:
            continue
        if abs(x-y) == 2:
            print(i, j)

## If you want them stored in lists in a dictionary:
d = {}
for i, x in enumerate(l):
    for j, y in enumerate(l):
        if j &lt;= i:
            continue
        if abs(x-y) == 2:
            k = 'p_{}'.format(x+1)
            try:
                d[k].append((i,j))
            except KeyError:
                d[k] = [(i,j)]
</code></pre>

python list loops