Easiest Way to Convert List of Hex Strings to List of Integers

5/5 - (2 votes)

💬 Question: Given a Python list of hexadecimal strings such as ['ff', 'ef', '0f', '0a', '93']. How to convert it to a list of integers in Python such as [255, 239, 15, 10, 147]?

Easiest Answer

The easiest way to convert a list of hex strings to a list of integers in Python is the list comprehension statement [int(x, 16) for x in my_list] that applies the built-in function int() to convert each hex string to an integer using the hexadecimal base 16, and repeats this for each hex string x in the original list.

Here’s a minimal example:

my_list = ['ff', 'ef', '0f', '0a', '93']
my_ints = [int(x, 16) for x in my_list]

# [255, 239, 15, 10, 147]

The list comprehension statement applies the expression int(x, 16) to each element x in the list my_list and puts the result of this expression in the newly-created list.

The int(x, 16) expression converts a hex string to an integer using the hexadecimal base argument 16. A semantically identical way to write this would be int(x, base=16).

In fact, there are many more ways to convert a hex string to an integer—each of them could be used in the expression part of the list comprehension statement.

However, I’ll show you one completely different approach to solving this problem without listing each and every combination of possible solutions. 👇

For Loop with List Append

You can create an empty list and add one hex integer at a time in the loop body after converting it from the hex string x using the eval('0x' + x) function call. This first creates a hexadecimal string with '0x' prefix using string concatenation and then lets Python evaluate the string as if it was real code and not a string.

Here’s an example:

my_list = ['ff', 'ef', '0f', '0a', '93']

my_ints = []
for x in my_list:
    my_ints.append(eval('0x' + x))

# [255, 239, 15, 10, 147]

You use the fact that Python automatically converts a hex value of the form 0xff to an integer 255:

>>> 0xff
>>> 0xfe
>>> 0x0f

You may want to check out my in-depth guide on this important function for our solution:

🌍 Recommended Tutorial: Python eval()