Numbers and their binary representation from 1 to 10


Creates a dictionary called binary_rep using a dictionary comprehension in Python. This dictionary maps numbers from 1 to 10 to their respective binary representations as strings. Here's a step-by-step explanation of the code:

  • binary_rep = {x: bin(x)[2:] for x in range(1, 11)}: This line creates the binary_rep dictionary using a dictionary comprehension. Here's how it works:
    • {x: bin(x)[2:] for x in range(1, 11)} is the dictionary comprehension. It iterates over the range of numbers from 1 to 10 (inclusive).
    • For each number x, it creates a key-value pair in the dictionary. The key (x) is the number itself, and the value (bin(x)[2:]) is calculated by converting x to its binary representation using the bin function and then removing the first two characters (which are '0b') from the binary string to get the binary representation as a string.
  • print(binary_rep): This line prints the binary_rep dictionary to the console.

Source Code

binary_rep = {x: bin(x)[2:] for x in range(1, 11)}
print(binary_rep)

Output

{1: '1', 2: '10', 3: '11', 4: '100', 5: '101', 6: '110', 7: '111', 8: '1000', 9: '1001', 10: '1010'}

Example Programs