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>Something like this, maybe?</p>

<pre><code>&gt;&gt;&gt; import itertools
&gt;&gt;&gt; import numbers
&gt;&gt;&gt; lst = ["a", 1, 2, 3, "b", 4, 5, 6]
&gt;&gt;&gt; groups = itertools.groupby(lst, key=lambda x: isinstance(x, numbers.Number))
&gt;&gt;&gt; result = [[x for x in group_iter] for is_number, group_iter in groups if is_number]
&gt;&gt;&gt; result
[[1, 2, 3], [4, 5, 6]]
</code></pre>

<p>And here is a less âsexyâ version that outputs a list of tuple pairs <code>(group_key, group_numbers)</code>:</p>

<pre><code>&gt;&gt;&gt; import itertools
&gt;&gt;&gt; import numbers
&gt;&gt;&gt; lst = ["a", 1, 2, 3, "b", 4, 5, 6]
&gt;&gt;&gt; groups = itertools.groupby(lst, key=lambda x: isinstance(x, numbers.Number))
&gt;&gt;&gt; group_key = None
&gt;&gt;&gt; result = []
&gt;&gt;&gt; for is_number, group_iter in groups:
...     if not is_number:
...         for x in group_iter:
...             group_key = x
...     else:
...         result.append((group_key, [x for x in group_iter]))
&gt;&gt;&gt; result
[('a', [1, 2, 3]), ('b', [4, 5, 6])]
</code></pre>

<p>Note that it is a quick and dirty version which expects the input data to be well-formed.</p>

python iteration