The itertools function groupbyis for this kind of thing. Some of the other answers here create a dictionary that is very reasonable, but if you really don't want to dict, then you can do this:
from itertools import groupby
from operator import itemgetter
A = ['T', 'D', 'Q', 'D', 'D']
sessionid = [1, 1, 1, 2, 2]
for k, g in groupby(zip(sessionid, A), itemgetter(0)):
print('{}: {}'.format(k, list(list(zip(*g))[1])))
Output
1: ['T', 'D', 'Q']
2: ['D', 'D']
operator.itemgetter(0)returns a called object that retrieves an element at index 0 of any object that you pass it; groupbyuses this as a key function to determine which items can be grouped together.
, , sessionid . , , zip(sessionid, A), , groupby.
, Python 2 Python 3