Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Remove list(s) from list of lists (Similar functionality to .pop() )

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

.pop() has the capacity to not only remove an element of a list but also return that element.

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

E.g is there a function that will remove [4,5,6] from the above list a, and return it.

The reason for the question is that I'm sorting a list through itemgetter and there's a collision between the headings row (string) and the rest of the data (datetime). As such, I'm looking to effectively pop the list which represents the headings, do a sort, then insert it back in.

like image 443
Phoenix Avatar asked Feb 18 '14 17:02

Phoenix


1 Answers

The nested lists are just values in the outer list. Just use .pop() on that outer 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 could just use a slice to remove the first row from consideration if a header row is in the way:

result = rows[:1] + sorted(rows[1:], key=itemgetter(1))
like image 171
Martijn Pieters Avatar answered Oct 28 '22 01:10

Martijn Pieters