w3resource

Python: Convert a given decimal number to binary list

Python List: Exercise - 185 with Solution

Write a Python program to convert a given decimal number to a binary list.

Sample Solution:

Python Code:

def decimal_to_binary_list(n):
    result = [int(x) for x in list('{0:0b}'.format(n))]
    return result
n = 8
print("Original Number:",n)
print("Decimal number (",n,") to binary list:")
print(decimal_to_binary_list(n))
n = 45
print("\nOriginal Number:",n)
print("Decimal number (",n,") to binary list:")
print(decimal_to_binary_list(n))
n = 100
print("\nOriginal Number:",n)
print("Decimal number (",n,") to binary list:")
print(decimal_to_binary_list(n))

Sample Output:

Original Number: 8
Decimal number ( 8 ) to binary list:
[1, 0, 0, 0]

Original Number: 45
Decimal number ( 45 ) to binary list:
[1, 0, 1, 1, 0, 1]

Original Number: 100
Decimal number ( 100 ) to binary list:
[1, 1, 0, 0, 1, 0, 0]

Pictorial Presentation:

Python List: Convert a given decimal number to binary list.

Flowchart:

Flowchart: Convert a given decimal number to binary list.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to form Bigrams of words in a given list of strings.
Next: Write a Python program to swap two sublists in a given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Decapitalizes the first letter of a string:

Example:

def tips_decapitalize(s, upper_rest=False):
  return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])
print(tips_decapitalize('PythonTips'))
print(tips_decapitalize('PythonTips', True)) 

Output:

pythonTips
pYTHONTIPS

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook