Home > Enterprise >  how do you remove the nth item in a list until only one element is left in the list in python
how do you remove the nth item in a list until only one element is left in the list in python

Time:11-23

So in this program, i have:

n = int(input())

p1 = 'One'

p2 = 'Two'

p3 = 'Three'

p4 = 'Four'

p5 = 'Five'


list = [p1, p2, p3, p4, p5]

while len(list) > 1:
if len(list) > n 1:
    n = n-1
list.pop((n) % len(list))
print (list)

For example, n = 3 and the desired output is P4 so i have to remove p3. after p3 is removed, i will remove again the nth item but the count will start on the item after the last removed item. since i removed p3, i have to start the count on p4. how do i start the count in p4? the loop i did counts from the very start of the list which is p1.

CodePudding user response:

I edited my suggestion.. hope I understood better what u looking for.

CodePudding user response:

After you initial code, here's the suggestion:

n=3

init_n=1

while len(l) > n init_n:

  l.pop(n init_n-1)

  init_n = init_n   n -1

print (list)

  • Related