[Tutor] nested list help

Evert Rol evert.rol at gmail.com
Tue Jul 27 15:48:38 CEST 2010


> Suppose i have this nested list:
> 
> >>> x
> [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]
> >>> for i in x:
> ...   print i
> ... 
> ['NM100', 3, 4, 5, 6, 7]
> ['NM100', 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>> 
> 
> how do i obtain from the above the following nested list:
> 
> >>> z
> [['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]

You're not saying exactly how you go from one list to the other (ie, what criterion you use to combine the inner lists).
You could remove combine the first two lists using extend(), whereby you pass all but the first element of the second inner list to extend(): list1.extend(list2[1:]). Or simply list1+list2[1:].
If you're not concerned about the order of the elements (though I guess you are), you could do things like list(set(list1+list2)).
On the other hand, if you want to combine lists based on their first element, consider using dictionaries and extend lists which have the same key. Depending on how you create the lists (eg, when reading columns from a file), you can actually do this during creationi.
Otherwise, a (double) for-loop and an if-statement would probably work and be relatively straightforward, but I guess that would be rather un-Pythonesque.


> >>> for i in z:
> ...   print i
> ... 
> ['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>> 




More information about the Tutor mailing list