EL323 EL323 - 4 years ago 111
Python Question

Removing multiple of 3 index from list

I want to remove multiple of 3 indexes 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:


How can I achieve this?

Answer Source

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']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download