Suppose I have a list:
lst = [0, 1, 0, 0]
How can I make python interpret this list as a binary number 0100 so that 2*(0100)
gives me 01000
?
The only way that I can think of is to first make a function that converts the "binary" elements to corresponding integers(to base 10) and then use bin() function..
Is there a better way?
We can convert the list into a set using the set() command, where we have to insert the list name between the parentheses that are needed to be converted. Hence, in the above case, we have to type the set(the_names) in order to convert the names, present in the list into a set.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
This basic method to convert a list of strings to a list of integers uses three steps: Create an empty list with ints = [] . Iterate over each string element using a for loop such as for element in list . Convert the string to an integer using int(element) and append it to the new integer list using the list.
You can use bitwise operators like this:
>>> lst = [0, 1, 0, 0]
>>> bin(int(''.join(map(str, lst)), 2) << 1)
'0b1000'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With