Removing every nth element from a list until two elements remain in python3
<p>modeling a game of Russian roulette where the contestants stand in a circle.
-every 7th contestant loses until 2 are left alive.</p>

<pre><code>contestants = list(range(1, 51))
dead_men = []
dead_man = 6

while len(contestants) &gt; 2:
    if dead_man &gt; len(contestants):
        dead_man = dead_man - len(contestants)
    loser = contestants.pop(dead_man)
    dead_men.append(loser)
    dead_man += 6
</code></pre>

<p>This gives me an index error with an index of 9 when my list length is 8</p>

<p>I assume you meant <code>contestants</code> instead of <code>soldiers</code> everywhere?</p>

<p>If so, then I think you just need:</p>

<pre><code>while dead_man &gt;= len(contestants):
</code></pre>

<p>(<code>while</code> rather than <code>if</code> in case you need to subtract multiple times, and <code>&gt;=</code> rather than just <code>&gt;</code> since indexes always need to be less than the length of the list)</p>

<p>You might also use <code>dead_man %= len(contestants)</code>. This uses module arithmetic.</p>

<p>My favorite way to do this sort of thing with the modulo trick:</p>

<pre><code>contestants = list(range(1, 51))
dead_men = []
dead_man = 6 % len(contestants)

while len(contestants) &gt; 2:
    loser = contestants.pop(dead_man)
    dead_men.append(loser)
    dead_man = (dead_man + 6) % len(contestants)
</code></pre>

python