EL323 EL323 - 3 months ago 10
Python Question

Removing every third item from list

I want to remove every 3rd item from list.
For Example:

list1 = list(['a','b','c','d','e','f','g','h','i','j'])


After removing indexes which are multiple of three the list will be:

['a','b','d','e','g','h','j']


How can I achieve this?

Answer

You may use enumerate():

>>> x = ['a','b','c','d','e','f','g','h','i','j']
>>> [i for j, i in enumerate(x) if (j+1)%3]
['a', 'b', 'd', 'e', 'g', 'h', 'j']

Alternatively, you may create the copy of list and delete the values at interval. For example:

>>> y = list(x) # where x is the list mentioned in above example
>>> del y[2::3] # y[2::3] = ['c', 'f', 'i']
>>> y
['a', 'b', 'd', 'e', 'g', 'h', 'j']