Iterating over only a part of list in Python
<p>I have a list in python, that consists of both alphabetic and numeric elements, say something like <code>list = ["a", 1, 2, 3, "b", 4, 5, 6]</code> and I want to slice it into 2 lists, containing numbers that follow the alphabetic characters, so <code>list1 = [1, 2, 3]</code> and <code>list2 = [4, 5, 6]</code>. <code>a</code> and <code>b</code> elements could be in reversed order, but generally, I want to store numeric elements that follow <code>a</code> and <code>b</code> elements in separate lists. The easiest solution that I came up with was creating a loop with condition:</p>

<pre><code>    #Generating a list for numeric elements following "a":
    for e in list[list.index("a")+1:]:
      if not str.isdigit(e):
       break
      else:
       list1.append(e)
</code></pre>

<p>I'd do it similarly for <code>list2</code> and numeric elements after <code>"b"</code>.
But could there be more elegant solutions? I'm new to Python, but I've seen beautiful one-liner constructions, could there be something like that  in my case? Thanks in advance. </p>

<p>Here you have a functional aproach:</p>

<pre><code>&gt;&gt;&gt; l = ["a", 1, 2, 3, "b", 4, 5, 6]
&gt;&gt;&gt; dig = [x for (x, y) in enumerate(l) if type(y) is str] + [len(l)]
&gt;&gt;&gt; dig
[0, 4, 8]
&gt;&gt;&gt; slices = zip(map(lambda x:x+1, dig), dig[1:])
&gt;&gt;&gt; slices
[(1, 4), (5, 8)]
&gt;&gt;&gt; lists = map(lambda (i, e): l[i:e], slices)
&gt;&gt;&gt; lists
[[1, 2, 3], [4, 5, 6]]
</code></pre>

<p>First we get the index of the letters with, notice that we need the size of the list to know the end of it:</p>

<pre><code>[x for (x, y) in enumerate(l) if type(y) is str] + [len(l)]
</code></pre>

<p>Then we get the pair of slices where the lists are:</p>

<pre><code>zip(map(lambda x:x+1, dig), dig[1:])
</code></pre>

<p>Finally, we get each slice from the original list:</p>

<pre><code>map(lambda (i, e): l[i:e], slices)
</code></pre>

python iteration