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>You can use slices:</p>

<pre><code>list = ["a", 1, 2, 3, "b", 4, 5, 6]
lista = list[list.index('a')+1:list.index('b')]
listb = list[list.index('b')+1:]
</code></pre>

python iteration