# [Tutor] manipulating list of lists

Brian van den Broek broek at cc.umanitoba.ca
Tue Oct 25 04:46:47 CEST 2005

```Vincent Gulinao said unto the world upon 2005-10-24 09:29:
> I have a list of lists of constant width (2 rows). I need to:
> 1. delete sub-lists with None element
> 2. sort it by any sub-list index
>
> say: [ ['c','d'], ['g',None], ['a','b',], ['e','f']
> if sorted using 2nd index: [ ['a','b'], ['c','d'], ['e','f'] ] (same result
> for 1st index for this example)
>
> TIA.

Hi Vincent,

I'm no guru, so watch this space for better suggestions ;-)

I changed your example to one where the sort order is different for
sort by the first and second items of the nested lists.

I'd use a list comprehension to remove the items with a None value:

>>> orig_list = [ ['c','b'], ['g',None], ['a','g',], ['e','f'], ['d',
None]]
>>> noneless = [[x, y] for [x, y] in orig_list if not (x is None or y
is None)]
>>> noneless
[['c', 'b'], ['a', 'g'], ['e', 'f']]

Or:
>>> noneless = [[x, y] for [x, y] in orig_list if not None in [x, y]]
>>> noneless
[['c', 'b'], ['a', 'g'], ['e', 'f']]

To sort by the second item, try

>>> def sort_by_second(sequence):
decorated = [(x[1], x) for x in sequence]
decorated.sort()
return [x[1] for x in decorated]

>>> sort_by_second(noneless)
[['c', 'b'], ['e', 'f'], ['a', 'g']]

HTH. There's no explanation here (I'm feeling lazy); post again if you
need some help sorting this out.

Best,

Brian vdB

```