Say:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I know that list[::2]
would remove every second element, so list = [1,3,5,7,9]
What if say I then needed to remove every third element? So list would become [1,3,7,9]
(5 would be removed since it is the third element. How would I then proceed to do that?
Currently, using b = list[::3]
returns [1, 7]
To delete elements from a given list, use del
:
del lst[::2] # delete every second element (counting from the first)
del lst[::3] # delete every third
Demo:
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del lst[::2]
>>> lst
[2, 4, 6, 8, 10]
>>> del lst[::3]
>>> lst
[4, 6, 10]
If you wanted to delete the second element counting from the second, you'd need to give the slice a starting index other than the default:
del lst[1::2] # delete every second element, starting from the second
del lst[2::3] # delete every third element, starting from the third
Demo:
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del lst[1::2]
>>> lst
[1, 3, 5, 7, 9]
>>> del lst[2::3]
>>> lst
[1, 3, 7, 9]
Your initial statement saves every other value it does not delete it. You should also not make your variable "list".
given the original values you show above
del mylist[::2]
will return the even values of the list while
del mylist[1::2]
will return the odd values as you request. Following that the standard
del mylist[::3]
will remove the third value of the list as you wanted.
For the incredibly long one-liner:
>>> [el for i,el in enumerate([el for i,el in enumerate([1,2,3,4,5,6,7,8,9,10]) if (i+1)%2]) if (i+1)%3]
[1,3,7,9]
Pseudocode for the above:
for (index, value) in [1,2,3,4,5,6,7,8,9,10]:
if index+1 is divisible by 2: toss it
else: add it to new_list
for (index, value) in new_list:
if index+1 is divisible by 3: toss it
else: add it to final_list
print(final_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With