Advanced python list manipulation