0

I have 2 lists (unique elements) (mainly lists of strings).

l1 = ['a','b','c']
l2 = ['c','b','a']

and I would like to have a function:

def foo_id(list)

where it generates an id based on their elements but without taking into account the order of the elements in my list.

i.e

foo_id(l1) == foo_id(l2)
Jibrilat
  • 308
  • 2
  • 12
  • 4
    Could you convert the `lists` to `sets`? – fredtantini Sep 11 '19 at 07:47
  • 1
    Do you care about repeating elements in your list? – Itamar Mushkin Sep 11 '19 at 07:54
  • The elements in the list will be unique in any case – Jibrilat Sep 11 '19 at 08:01
  • Excuse me for my ignorance but this is more a question of "How I can do that" and not "why this is happening" Therefore I don't understand why it should include any trial and error attempts. I can imagine there are bad question patterns like "Do this work for me" but in my case, I tried to formulate a minimal question with the necessary foo code in order to get a simple answer i.e "use this foo.foobar function". In simple words, I find the downvoting a bit unfair :) Cheers – Jibrilat Sep 11 '19 at 08:40

2 Answers2

1

You could generate unique ids as follows.

import hashlib # provides many hash functions including md5, sha1, sha2, etc.

l1 = ['a','b','c']
l2 = ['c','b','a']

def genereate_id(l):
  s = str(sorted(l))    
  s_unicode = s.encode('utf-8') # hashlib requires unicode
  return hashlib.md5(s_unicode).hexdigest()

print(genereate_id(l1)) # eea457285a61f212e4bbaaf890263ab4
print(genereate_id(l2)) # eea457285a61f212e4bbaaf890263ab4
DarrylG
  • 11,572
  • 2
  • 13
  • 18
1

Try this code:

from hashlib import blake2b

def foo_id(l):
    h = blake2b()
    h.update(str(sorted(l)).encode('ascii'))
    return h.hexdigest()

l1 = ['a','b','c']
l2 = ['c','b','a']
foo_id(l1) == foo_id(l2)
# output: True

Note:
It is not possible to directly use the Python hash() since in executions it would give different results: this is because from Python3 the hash() function is associated with a session seed(PYTHONHASHSEED) for generating random numbers. Find more information in this post.

Massifox
  • 3,727
  • 8
  • 26