Home > Software engineering >  How to write a nested loop for elements of a list so that the combination of elements is not repeate
How to write a nested loop for elements of a list so that the combination of elements is not repeate

Time:09-27

My current code is:-

team=['Dragons','Wolves','Nightriders','Lords']
for home_team in team:
    for away_team in team:
        if home_team!=away_team:
            print(home_team,"vs",away_team)

For which the output is

Dragons vs Wolves

Dragons vs Nightriders

Dragons vs Lords

Wolves vs Dragons

Wolves vs Nightriders

Wolves vs Lords

Nightriders vs Dragons

Nightriders vs Wolves

Nightriders vs Lords

Lords vs Dragons

Lords vs Wolves

Lords vs Nightriders

Now I want to alter this code so that two teams don't face each other twice for eg. if there is Wolves vs Lords there shouldn't be Lords vs Wolves

CodePudding user response:

You can start the nested for loop after the current index, because the previous words are already matched.

team=['Dragons','Wolves','Nightriders','Lords']

for i in range(len(team)):
    for j in range(i   1, len(team)):  
        print(team[i], ' vs ', team[j])

  • Related