I have a simple, always-consecutive-ordered list like this:
all = [ 1, 2, 3, 4, 5, 6 ] # same as range( 1, 7 )
I also have current = 4
. In the end I want the all
list to look like this
altered = [ 1, 2, 5, 6 ]
So what happened was it removed the current
number and the one before it 3
.
current
can also be 1
and 0
, so I want to make sure it doesn't throw an error for those two values.
For the exception current = 0
, the altered list is like this
altered = [ 1, 2, 3, 4, 5 ]
Which means that current = 0
simply removes the last number.
I feel like you can probably code something fancy with generators, but I suck at writing them.
Thanks in advance!
Bonus points for doing this in one line. If the current = 0
is too much trouble, then it could also be current = -1
or current = 7
.
EDIT: Make sure to check for current = 1
, which should be
altered = [ 2, 3, 4, 5, 6 ]
Remove Multiple elements from list by index range using del. Suppose we want to remove multiple elements from a list by index range, then we can use del keyword i.e. It will delete the elements in list from index1 to index2 – 1.
Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.
all = all[:max(current - 2, 0)] + all[current:]
or
del all[max(current - 2, 0):current]
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