# Python 2.7: Lambda and Bitwise Operators

Hands-On | 29 Nov 2016
Tags:

# Lambda functions

Using lambda functions we can create functions in runtime, and use them as we go. Here's an example of lambda function and how it is used to filter the array. filter() function takes the lambda function as the first parameter, passes items of the list sequentially and filters the list to retain the items which pass the filtration function passed as first argument.

# will assign a range of numbers from 0 to 15 to numbers list
numbers = range(16)

# output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print numbers

# filtering only numbers which can be divided by 3
filtered_numbers = filter(lambda x: x % 3 == 0, numbers)

# output: [0, 3, 6, 9, 12, 15]
print filtered_numbers


# Bitwise Operators

Bitwise operators directly manipulate bits. Python provides certain set of operatos. Example:

print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT

# output: 0
# output: 10
# output: 0
# output: 13
# output: 38
# output: -89

### Base 2 number system

# convert binary to decimal
print 0b1 # output 1
print 0b10 # output :2
print 0b11 # output: 3
print 0b10 + 0b01 # output: 3

# convert decimal to binary
# output:0b1111
print bin(15)

# convert decimal to base-8
# output: 017
print oct(15)

# convert decimal to base-16 / hexedecimal
# output: 0xe
print oct(14)

### Converting string to number

# converting string from base 10 number
# output: 10
print int("10")

# converting string from base 2 number
# output: 2
print int("10", 2)

# converting string from base 16 number
# output: 204
print int("cc", 16)

### Other Operators

# bitwise AND
# output: 0b001
print bin(0b101 & 0b011)

# bitwise OR
# output: 0b111
print bin(0b101 | 0b011)

# bitwise XOR
# output: 0b110
print bin(0b101 ^ 0b011)

# bitwise NOT
# flips all the bits in a number
# output: -0b110
print bin(~0b101)

### Check if the bit #5 is on or off

def check_bit5(number):
if number & 0b10000 > 0:
return 'on'
else:
return 'off'

# output: on
print check_bit5(0b111101)

# output: off
print check_bit5(0b101101)

### Flipping the nth bit in a number

# will flip the nth bit in the number
def flip_bit(number, n):
mask = 1 << (n - 1)
print flip_bit(0b100000, 3)