Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete sublist from a list

Tags:

python

list

I want to delete a sublist from a list. I only know the starting index and the ending index. how can I delete from the list?

I'm using the following code:

def delete_sub_list( self, cmd_list, start, end ):
        tmp_lst = []
        for i in range( len( cmd_list ) ):
            if( i < start or i > end ):
                tmp_lst.append( cmd_list[ i ] )

        return tmp_lst

and I'm calling in the following way:

cmd_list = self.delete_sub_list( cmd_list, 4, 14 )
like image 870
OHLÁLÁ Avatar asked Dec 22 '22 06:12

OHLÁLÁ


1 Answers

The Python syntax to do this is

del cmd_list[4:14 + 1]

(The + 1 is necessary to match your code. Python uses half-open intervals, i.e. the first index is included in the slice, but the last isn't.)

like image 67
Sven Marnach Avatar answered Jan 07 '23 09:01

Sven Marnach