Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: UUID in a list

I have a list with a uuid4 in it. I also have a string. For example:

list = [UUID('79d8f4b7-06a0-41d1-99d6-dd8c5308875f'), 'example1', 'example2']
string = 79d8f4b7-06a0-41d1-99d6-dd8c5308875f

But when I try:

if string in list:
    print("It's in!")
else:
    print("It's not!")

The output is always "it's not".

I know there is probably a data type error going on but i cant seem to find it myself. Any help is appreciated, i'm sure something this simple will be fixed within seconds, thanks in advance.

When I type print list[0] this is what is output: 79d8f4b7-06a0-41d1-99d6-dd8c5308875f. But even when i try say "..in list[0]", it still doesn't work.

like image 370
tester Avatar asked Sep 11 '25 02:09

tester


1 Answers

You need to convert uuid to string with str() function .

>>> import uuid
>>> x=uuid.uuid4()
>>> str(x)
'924db46b-5c51-4330-861c-363570ea9ef6'

and for check you need to convert string to uuid ,with uuid.UUID but as this function accept bytes you need to pass the bytes of your string to it :

>>> my_list = [x, 'example1', 'example2']
>>> uuid.UUID(bytes=x.bytes) in my_list
True
like image 86
Mazdak Avatar answered Sep 12 '25 16:09

Mazdak