Iterating through list (Python)
<pre><code>collection = ["81851 19AJA01", "68158 17ARB03", "104837 20AAH02", 
</code></pre>

<p>I have a list that extends on like this and I would like to sort them based on the first 2 digits of the second part of each. I'm really rushed right now so some help would be nice. </p>

<p>I tried this and it didn't work. I'm not doing this for a class I'd really appropriate some help </p>

<pre><code>for x in collection:
counter = 0
i=0
for y in len(str(x)):
    if (x[i] == '1'):
        counter == 1
    elif (x[i] == '2'):
        counter == 2
    elif x[i]  == '0' and counter == 2:
        counter = 2
    elif x[i]  == '9' and counter == 1:
        counter = 3
    elif x[i]  == '8' and counter == 1:
        counter = 4
    elif x[i] == '7' and counter == 1:
        counter = 5
    i = i + 1

if (counter==2):
    freshmen.append(x)
elif (counter==3):
    sophomores.append(x)
elif (counter==4):
    juniors.append(x)
elif (counter==5):
    seniors.append(x)
</code></pre>

<p>Use the <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>key</code> function</a> to define a custom sorting rule:</p>

<pre><code>In [1]: collection = ["81851 19AJA01", "68158 17ARB03", "104837 20AAH02"]

In [2]: sorted(collection, key=lambda x: int(x.split()[1][:2]))
Out[2]: ['68158 17ARB03', '81851 19AJA01', '104837 20AAH02']
</code></pre>

python