pythonlistdivide

PYTHON: Trying to divide elements alternately from a list to two already existing sublists in another list. No imports please


For context, I have a list of "players" ready. Let's say players = ['steve','gary','simon','kevin']. And I also have a list with two sublists with a "leader" in each of them: groups = [['leader1'],['leader2']]

Now, I need to distribute the players to their leaders alternately: groups = [['leader1','steve','simon'],['leader2','gary','kevin']]

I've been stumped on this task for quite some time and would greatly appreciate a little help. And also, no imports please, thanks!

I've already tried so many different ways of solving this, but to no avail. The following is one of the attempts I was really hopeful about:

for i in range(len(players))
   for j in range(len(groups))
      groups[j].append(players[i])

In retrospect, of course this wouldn't work but I was just really tired (and still am :D).


Solution

  • Your groups exist at indices 0 and 1. A trick for alternating between the two indices is to subtract each index from 1 to get the other.

    i = 0
    for p in players:
      groups[i].append(p)
      i = 1 - i  # 1 - 0 == 1, 1 - 1 = 0
    

    Using an import from the standard library (there's little reason to avoid it),

    from itertools import cycle
    
    for player, team in zip(players, cycle(groups)):
        team.append(player)
    

    Iterating over cycle(groups) just iterates over the contents repeatedly for as long as zip needs value. team is alternate set to groups[0], groups[1], groups[0], groups[1], etc, for as long as there is an available player for zip to pair with a group.