Python | Decimal to binary list conversion
The conversion of a binary list to a decimal number has been dealt in a previous article. This article aims at presenting certain shorthand to do the opposite, i.e binary to decimal conversion. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + format()
In this method, the conversion of the decimal to binary is handled by the format function. The logic of conversion to the list is done by the list comprehension function.
# Python3 code to demonstrate # decimal to binary number conversion # using format() + list comprehension # initializing number test_num = 38 # printing original number print ("The original number is : " + str(test_num)) # using format() + list comprehension # decimal to binary number conversion res = [int(i) for i in list('{0:0b}'.format(test_num))] # printing result print ("The converted binary list is : " + str(res)) |
The original number is : 38 The converted binary list is : [1, 0, 0, 1, 1, 0]
Method #2 : Using bin() + list comprehension
The inbuilt function bin performs the function of conversion to binary and the list comprehension handles the logic to convert the binary number to the list.
# Python3 code to demonstrate # decimal to binary number conversion # using bin() + list comprehension # initializing number test_num = 38 # printing original number print ("The original number is : " + str(test_num)) # using bin() + list comprehension # decimal to binary number conversion res = [int(i) for i in bin(test_num)[2:]] # printing result print ("The converted binary list is : " + str(res)) |
The original number is : 38 The converted binary list is : [1, 0, 0, 1, 1, 0]
Recommended Posts:
- Python | Dictionary to list of tuple conversion
- Python | List of tuples to dictionary conversion
- Binary to decimal and vice-versa in python
- Python | Decimal step range in list
- Python program to covert decimal to binary number
- Python | Binary list to integer
- Python | Binary element list grouping
- Python | Get indices of True values in a binary list
- Python | Key-Value to URL Parameter Conversion
- Type Conversion in Python
- Python | Timezone Conversion
- C strings conversion to Python
- HTML Cleaning and Entity Conversion | Python
- Python | Type conversion in dictionary values
- Python | Type conversion of dictionary items
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



