-1

I have a list of decimal numbers as integers, and I want to convert them into binary. The output must be without 0b prefix and also it must be 4 digits like:

lista = [1,2,3,4,5,6,7,8,9,10]
listres = [0001,0010,0011,0100,...]

thanks in advance

4
  • 1
    You mean you want to convert them to strings, right? Commented Oct 29, 2018 at 21:13
  • 1
    @roganjosh decimal as in decimal base, I suppose. Commented Oct 29, 2018 at 21:14
  • @roganjosh no worries ;) Commented Oct 29, 2018 at 21:17
  • What if the input list contains the number 20? Commented Oct 29, 2018 at 21:19

4 Answers 4

3

You can use map with format here, with '04b':

>>> list(map(lambda x: format(x,'04b'),lista))
['0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010']
Sign up to request clarification or add additional context in comments.

2 Comments

just like the above answer, the result of your code is string binary digits : ['0001', '0010', '0011', '0100', '0101'] but how can I obtain integer as result like : [0001, 0010, 0011, 0100, 0101]
You can't, those aren't integers if they're zero padded.
2

Another hacky way to achieve this is:

listres = [str(bin(x))[2:].zfill(4) for x in lista]

1 Comment

the result of your code is string binary digits : ['0001', '0010', '0011', '0100', '0101'] but how can I obtain integer as result like : [0001, 0010, 0011, 0100, 0101]
0

This sounds like homework, so I'll just give a recommendation on how to proceed in creating the second list. If you know how to convert an integer into a binary representation, then you can use a list comprehension:

lista = [1,2,3,4,5,6,7,8,9,10]
listb = [integer_to_binary(n) for n in lista]

Here integer_to_binary() is just a function that converts an integer into its binary representation. It sounds like what you want is a string showing the binary representation, so I'll leave that to you to figure out (hint: try using format())

1 Comment

no its not a homework. but thanks for recommendation
-1

Use bin method;

>>> a = bin(6)
>>>a

'0b110'
a[2:]
110

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.