[x for [x, y] in cache]
This will create a temporary list ['a', 'c']
which you use to check whether val
is contained in it. The list however is never kept around, so you can’t really access it. Since this is Python 2, the variables from within the list comprehension (x
and y
) actually leak out of the expression, so they are still around afterwards. But as you looped through cache
they will have the last values which are 'c'
and 'd'
respectively.
>>> [x for [x, y] in cache]
['a', 'c']
>>> x, y
('c', 'd')
Of course that’s not really helpful, and the variable leaking has been fixed in Python 3 (where both variables stay undefined after the list comprehension).
But to solve your problem, what you want to do, is to look up the x
from your cache, and then return the respective y
. You can do this simply by creating a dictionary that maps x
to y
:
>>> d = {x: y for x, y in cache}
>>> d
{'a': 'b', 'c': 'd'}
>>> if val in d:
print(d[val])
else:
print('Not found')
b
If you cache always contains sublists of two elements where the first one is used to look up things, then it’s a good idea to completely switch over to dictionaries. That way, you can have the lookup in constant time (which is very useful since you want a cache to be fast), and have a lot more control over it (like avoiding duplicate/old values).