I've got a system in which I often (but not constantly) have to find the next item in a tuple. I'm currently doing this like so:
mytuple = (2,6,4,8,7,9,14,3)
currentelement = 4
def f(mytuple, currentelement):
return mytuple[mytuple.index(currentelement) + 1]
nextelement = f(mytuple, currentelement)
All elements are unique and I am not stuck with the tuple, I can make it something else earlier in the program if needed.
Since I need to do this a lot, I was wondering whether there is any more efficient way to do this?
Use a dict here, dicts provide O(1)
lookup compared to list.index
which is an O(N)
operation.
And this will work for strings as well.
>>> 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') #dict.get can handle key errors
'not found'
A memory efficient version 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}