简体   繁体   中英

Delete sublist from a 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 )

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, ie the first index is included in the slice, but the last isn't.)

You can use either:

cmd_list[start:end + 1] = []

or

del cmd_list[start:end + 1]

Might be easiest to do it with slicing:

cmd_list = cmd_list[:start] + cmd_list[end+1:]

we still need end+1 for the second half, but it's still a pretty clear line of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM