Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty.
Examples:
Input : [10, 20, 30, 40, 50, 60, 70, 80, 90]
Output : 30 60 90 40 80 50 20 70 10
Explanation:
The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 60, after that 90 is encountered. Then again the count starts from 10 for the next third element which is 40. Proceeding in the same manner as we did before we get next third element after 40 is 80. This process is repeated until the list becomes empty.Input : [1, 2, 3, 4]
Output : 3 2 4 1
Explanation:
The first third element encountered is 3, after 3 we start the count from 4 for the next third element which is 2. Then again the count starts from 4 for the next third element which is 4 itself and finally the last element 1 is printed.
Approach The index of the list starts from 0 and the first third element will be at position 2. Traverse till the list becomes empty and each time find the index of the next third element and print its corresponding value. After printing reduce the length of the list.
# Python program to remove to every third # element until list becomes empty def removeThirdNumber(int_list): # list starts with # 0 index pos = 3 - 1 index = 0 len_list = (len(int_list)) # breaks out once the # list becomes empty while len_list > 0: index = (pos + index) % len_list # removes and prints the required # element print(int_list.pop(index)) len_list -= 1 # Driver code nums = [1, 2, 3, 4] removeThirdNumber(nums) |
Output:
3 2 4 1
Recommended Posts:
- Python | Remove empty tuples from a list
- Python | Remove trailing empty elements from given list
- Python | Remove empty strings from list of strings
- Python | Check whether a list is empty or not
- Python | First Non-Empty String in list
- Python | Splitting list on empty string
- Python | Remove all values from a list present in other list
- Python list remove()
- Python | Remove given element from the list
- Python | Remove Duplicates from a List
- Python | Remove None values from list
- Python | Remove last K elements of list
- Python | Remove all strings from a list of tuples
- Python | Remove additional spaces in list
- Python | Remove all occurrences in nested list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



