Python - Remove a list (list) from a list of lists (Similar functionality for .pop ())

a=[[1,2,3],[4,5,6],[7,8,9]]

.pop () has the ability to not only delete the list item, but also return this item.

I am looking for a similar function that can remove and return the entire list that may exist in the middle of another list.

For example, there is a function that will remove [4,5,6]from the list above aand return it.

The reason for the question is that I sort the list through itemgetterand there is a collision between the header lines (row) and the rest of the data ( datetime). Thus, I am looking to effectively pop up a list that represents the headers, pretend, and then insert it back.

+6
source share
1 answer

Nested lists are just the values ​​in an external list. Just use .pop()in this external list:

inner_list = a.pop(1)

Demo:

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a.pop(1)
[4, 5, 6]
>>> a
[[1, 2, 3], [7, 8, 9]]

You can simply use slice to remove the first line from consideration if the title bar is in the path:

result = rows[:1] + sorted(rows[1:], key=itemgetter(1))
+16
source

Source: https://habr.com/ru/post/1527561/


All Articles