Use dict here, dicts provides an O(1) list.index compared to list.index , which is an O(N) operation.
And this will work for strings too.
>>> lis = (2,6,4,8,7,9,14,3) >>> dic = dict(zip(lis, lis[1:])) >>> dic[4] 8 >>> dic[7] 9 >>> dic.get(100, 'not found')
Effective version with memory to create the above dict:
>>> from itertools import izip >>> lis = (2,6,4,8,7,9,14,3) >>> it1 = iter(lis) >>> it2 = iter(lis) >>> next(it2) 2 >>> dict(izip(it1,it2)) {2: 6, 4: 8, 6: 4, 7: 9, 8: 7, 9: 14, 14: 3}
source share