I'm trying to add a value to a list but only if it hasen't been added yet.
Is there a command to do this or is there a way to test for the existence of a value within a list?
Thanks!
Checking a list to see if a member exists within it is O(n), which can get quite expensive for big lists and is definitely not ideal. That said, everyone else seems to be giving you alternatives. I'll just tell you how to do what you're asking to do, and assume you have good reasons for doing it the way you're doing it. I'll do it in Python, assuming you have a connection to Redis called r, some list called some_list and some new item to add called new_item:
lst = r.lrange(list_name, -float('Inf'), float('Inf'))
if new_item not in lst:
r.rpush(list_name, new_item)
It looks like you need a set or a sorted set.
Sets have O(1) membership test and enforced uniqueness.
Such feature is available in set using hexistshexists command in redis.
I need to do the same. I think about to remove the element from the list and then add it again. If the element is not in the list, redis will return 0, so there is no error
lrem mylist 0 myitem
rpush mylist myitem