vendredi 26 mars 2021

Looping the list to get the last item

I want to get a single item in a list at last when the loop completes it's run,

word = 'DOOR'
# so the length of word is 4

actual_list = ['A', 'B', 'C', 'D', 'E', 'F']

Here, i want to run a loop on the actual_list with the length of the variable word, when the loop completed, it shows the last item present in the list. When i did this problem using pen and paper, i got the item E which is not removed by the loop. I also tried this code, but i couldn't got the result successfully,

word = 'DOOR'
print(len(word))

actual_list = ['A', 'B', 'C', 'D', 'E', 'F']

for w in actual_list[:]:
    if len(actual_list) > 1:
        del actual_list[len(word)-1]
        print(actual_list)

Explanation:
The loop remove the 4th item in the list and again the loop will run from the next item after the first item got removed,
Example: after the first loop['A', 'B', 'C', 'E', 'F'] , after the second loop ['A', 'C', 'E', 'F'] , after the third loop ['C', 'E' ,'F'], after the fourth loop ['E', 'F'] , after the fifth loop ['E'] likewise, loop continue it's run from the next item where it remove the last item.
When i run the above code, it says, the index gets out of range, i have been stuck here for almost 4 days. I want the result as,

# The last item in the list
['E']

Can anyone have solution for this?

Aucun commentaire:

Enregistrer un commentaire