
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Binary list to integer in Python
We can convert a list of 0s and 1s representing a binary number to a decimal number in python using various approaches. In the below examples we use the int() method as well as bitwise left shift operator.
Using int()
The int() method takes in two arguments and changes the base of the input as per the below syntax.
int(x, base=10) Return an integer object constructed from a number or string x.
In the below example we use the int() method to take each element of the list as a string and join them to form a final string which gets converted to integer with base 10.
Example
List = [0, 1, 0, 1, 0, 1] print ("The List is : " + str(List)) # binary list to integer conversion result = int("".join(str(i) for i in List),2) # result print ("The value is : " + str(result))
Running the above code gives us the following result −
The List is : [1, 1, 0, 1, 0, 1] The value is : 53
Using the Bitwise Left Shift Operator
The bitwise left shift operator converts the given list of digits to an integer after adding to zeros to the binary form. Then bitwise or is used to add to this result. We use a for loop to iterate through each of the digits in the list.
Example
List = [1, 0, 0, 1, 1, 0] print ("The values in list is : " + str(List)) # binary list to integer conversion result = 0 for digits in List: result = (result << 1) | digits # result print ("The value is : " + str(result))
Running the above code gives us the following result −
The values in list is : [1, 0, 0, 1, 1, 0] The value is : 38
- Related Articles
- Program to convert Linked list representing binary number to decimal integer in Python
- Convert Binary Number in a Linked List to Integer in C++
- Decimal to binary list conversion in Python
- Binary element list grouping in Python
- Convert list of string into sorted list of integer in Python
- Program to create linked list to binary search tree in Python
- How to convert Integer array list to integer array in Java?
- Python Program to Implement Binary Tree using Linked List
- Program to traverse binary tree using list of directions in Python
- Program to convert linked list to zig-zag binary tree in Python
- C# program to convert binary string to Integer
- Program to find minimum cost to reduce a list into one integer in Python
- Program to convert level order binary tree traversal to linked list in Python
- How do I convert an integer to binary in JavaScript?
- Java Program to convert an integer into binary
