Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a range (subsection) of a list in Python?

Tags:

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 ] 
like image 920
hobbes3 Avatar asked Apr 10 '12 07:04

hobbes3


People also ask

How do I remove multiple indices from a list in Python?

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.

How do I remove a sublist from a nested list in Python?

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.


1 Answers

all = all[:max(current - 2, 0)] + all[current:] 

or

del all[max(current - 2, 0):current] 
like image 146
Doboy Avatar answered Oct 20 '22 00:10

Doboy