-3

List of 4 items is given. I need to iteratively remove an item from the list. At each iteration I need to show: - What is removed - New list

I am trying this:

import random
teams=["Tottenham", "Ajax", "Barcelona", "Liverpool"] 
for i in teams:
    t1=random.randint(0, len(teams)-1)
    print(teams[t1])
    teams.remove(teams[t1])
    print(teams)

I am getting this:

Ajax

['Tottenham', 'Barcelona', 'Liverpool']

Liverpool

['Tottenham', 'Barcelona']

But should get something like this:

Ajax

['Tottenham', 'Barcelona', 'Liverpool']

Liverpool

['Tottenham', 'Barcelona']

Tottenham

['Barcelona']

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
novichok
  • 7
  • 4

1 Answers1

-1

You can shuffle the list first, then iterate over it:

import random

teams = ["Tottenham", "Ajax", "Barcelona", "Liverpool"]
random.shuffle(teams)

while teams:
    print(teams.pop())
    print(teams)

Output

Liverpool
['Ajax', 'Tottenham', 'Barcelona']
Barcelona
['Ajax', 'Tottenham']
Tottenham
['Ajax']
Ajax
[]

Note

To shuffle first reduces the complexity of the loop. It might not be applicable in all situations, but it is an option.

Cloudomation
  • 1,597
  • 1
  • 6
  • 15