1. What is _init_ in python?
it's an init() method in every call defined in Python.. to initialize like constructor like in java.
class Employee:
def __init__(self, name, age,salary): //self is an instance or an object of a class. In Python, this is explicitly included as the first parameter.
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
-----------------------------------------------------------------------------------------
2. Lambda function
a = lambda x,y : x+y
print(a(5, 6))
b = lambda x,y,z : (x+z)/y
print(b(9,3,6))
-----------------------------------------------------------------------------------------
3. What does [::-1] do?
A. It reverse's the array.
import array as arr
My_Array=arr.array('i',[1,2,3,4,5])
My_Array[::-1]
Output: array(‘i’, [5, 4, 3, 2, 1])
-----------------------------------------------------------------------------------------
4. How can you randomize the items of a list in place in Python?
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
O/P: ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
Generate Random numbers>
import random
random.random
-----------------------------------------------------------------------------------------
5. What is the purpose of 'is', 'not' and 'in' operators?
'is' - checks if two operends are same of not if 'a' is "a" (returns boolean)
'not' - check if they are inverse
'in' - checks if an operand is present in List or String.
-----------------------------------------------------------------------------------------
6. Dictionary
dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
dict['Country']
'India'
-----------------------------------------------------------------------------------------
7. Keywords in Python
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
NONE: //None does not imply False, 0 or any empty list, dictionary, string etc.
>>> None == 0
False
>>> None == []
False
>>> None == False
False
>>> x = None
>>> y = None
>>> x == y
True
del
del is used to delete the reference to an object.
>>> a = b = 5
>>> del a
>>> a
>>> a = ['x','y','z']
>>> del a[1]
>>> a
['x', 'z']
-----------------------------------------------------------------------------------------
Break, Continue
for i in range(1,11):
if i == 5:
break
print(i)
O/P //up to 4
1
2
3
4
for i in range(1,11):
if i == 5:
continue
print(i)
O/P // 5 is missing
1
2
3
4
6
7
8
9
10
FOR:
names = ['John','Monica','Steven','Robin']
for i in names:
print('Hello '+i)
WHILE:
i = 5
while(i):
print(i)
i = i – 1
-----------------------------------------------------------------------------------------
pass
pass is a null statement in Python. Nothing happens when it is executed. It is used as a placeholder.
def function(args):
pass
class example:
pass
-----------------------------------------------------------------------------------------
x = (1 == True)
y = (1 == False)
a = True + 4 // 1 + 4
b = False + 10 // 0 + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
x is True
y is False
a: 5
b: 10
-----------------------------------------------------------------------------------------
fruits = ["apple", "mango", "orange"] #list
numbers = (1, 2, 3) #tuple
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels = {'a', 'e', 'i' , 'o', 'u'} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
['apple', 'mango', 'orange']
(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}
We can even convert one sequence to another.
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
-----------------------------------------------------------------------------------------
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'
-----------------------------------------------------------------------------------------
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
x = True
y = False
# Output: x and y is False
print('x and y is',x and y)
# Output: x or y is True
print('x or y is',x or y)
# Output: not x is False
print('not x is',not x)
-----------------------------------------------------------------------------------------
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)
-----------------------------------------------------------------------------------------
Assignment operators
Operator Example Equivatent to
= x = 5 x = 5
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x = x & 5
|= x |= 5 x = x | 5
^= x ^= 5 x = x ^ 5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
-----------------------------------------------------------------------------------------
Python Recursive Function
We know that in Python, a function can call other functions.
It is even possible for the function to call itself. These type of construct are termed as recursive functions.
# An example of a recursive function to
# find the factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
FLOW:
calc_factorial(4) # 1st call with 4
4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
4 * 3 * 2 # return from 3rd call
4 * 6 # return from 2nd call
24 # return from 1st call
-----------------------------------------------------------------------------------------
Python Anonymous/Lambda Function
In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Syntax of Lambda Function in python
lambda arguments: expression
Example:1
double = lambda x: x * 2
# Output: 10
print(double(5))
Example:2 //filter
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
# Output: [4, 6, 8, 12]
print(new_list)
Example:3 //map
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)
-----------------------------------------------------------------------------------------
import math
# Output: 3.141592653589793
print(math.pi)
# Output: -1.0
print(math.cos(math.pi))
# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))
# Output: 1.1752011936438014
print(math.sinh(1))
# Output: 720
print(math.factorial(6))
-----------------------------------------------------------------------------------------
import random
# Output: 16
print(random.randrange(10,20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
print(random.random())
-----------------------------------------------------------------------------------------
LIST:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
-|
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
-|
# mistake values
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
-|
We can add one item to a list using append() method or add several items using extend() method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)
-|
We can also use + operator to combine two lists
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
-|
The * operator repeats a list for the given number of times.
#Output: ["re", "re", "re"]
print(["re"] * 3)
-|
Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
-|
How to delete or remove elements from a list?
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
# delete multiple items
del my_list[1:5]
# Output: ['p', 'm']
print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)
-|
# remove() method to remove the given item
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# pop(i) method to remove an item at the given index.
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# pop() method removes and returns the last item if index is not provided.
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
clear() method to empty a list.
my_list.clear()
# Output: []
print(my_list)
delete items in a list by assigning an empty list to a slice of elements.
>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']
-|
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
my_list = [3, 8, 1, 6, 0, 8, 4]
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
-|
List Comprehension: Elegant way to create new List
pow2 = [2 ** x for x in range(10)]
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
same as
pow2 = []
for x in range(10):
pow2.append(2 ** x)
-|
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']
-|
my_list = ['p','r','o','b','l','e','m']
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
-----------------------------------------------------------------------------------------
Tuple: >> imutable list
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple) # Output: (1, "Hello", 3.4)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# Output: 3, 4.6, "dog"
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
-|
Creating a tuple with one element is a bit tricky.
my_tuple = ("hello") //creates a String
print(type(my_tuple)) # <class 'str'>
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
-|
Indexing:
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# IndexError: list index out of range
# print(my_tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
-|
Changing a Tuple (elements like List in Tuple can be changed)
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, item of mutable element can be changed
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
-|
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
-|
# Delete
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
-|
Method Description
count(x) Returns the number of items x
index(x) Returns the index of the first item that is equal to x
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
it's an init() method in every call defined in Python.. to initialize like constructor like in java.
class Employee:
def __init__(self, name, age,salary): //self is an instance or an object of a class. In Python, this is explicitly included as the first parameter.
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
-----------------------------------------------------------------------------------------
2. Lambda function
a = lambda x,y : x+y
print(a(5, 6))
b = lambda x,y,z : (x+z)/y
print(b(9,3,6))
-----------------------------------------------------------------------------------------
3. What does [::-1] do?
A. It reverse's the array.
import array as arr
My_Array=arr.array('i',[1,2,3,4,5])
My_Array[::-1]
Output: array(‘i’, [5, 4, 3, 2, 1])
-----------------------------------------------------------------------------------------
4. How can you randomize the items of a list in place in Python?
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
O/P: ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
Generate Random numbers>
import random
random.random
-----------------------------------------------------------------------------------------
5. What is the purpose of 'is', 'not' and 'in' operators?
'is' - checks if two operends are same of not if 'a' is "a" (returns boolean)
'not' - check if they are inverse
'in' - checks if an operand is present in List or String.
-----------------------------------------------------------------------------------------
6. Dictionary
dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
dict['Country']
'India'
-----------------------------------------------------------------------------------------
7. Keywords in Python
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
NONE: //None does not imply False, 0 or any empty list, dictionary, string etc.
>>> None == 0
False
>>> None == []
False
>>> None == False
False
>>> x = None
>>> y = None
>>> x == y
True
del
del is used to delete the reference to an object.
>>> a = b = 5
>>> del a
>>> a
>>> a = ['x','y','z']
>>> del a[1]
>>> a
['x', 'z']
-----------------------------------------------------------------------------------------
Break, Continue
for i in range(1,11):
if i == 5:
break
print(i)
O/P //up to 4
1
2
3
4
for i in range(1,11):
if i == 5:
continue
print(i)
O/P // 5 is missing
1
2
3
4
6
7
8
9
10
FOR:
names = ['John','Monica','Steven','Robin']
for i in names:
print('Hello '+i)
WHILE:
i = 5
while(i):
print(i)
i = i – 1
-----------------------------------------------------------------------------------------
pass
pass is a null statement in Python. Nothing happens when it is executed. It is used as a placeholder.
def function(args):
pass
class example:
pass
-----------------------------------------------------------------------------------------
x = (1 == True)
y = (1 == False)
a = True + 4 // 1 + 4
b = False + 10 // 0 + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
x is True
y is False
a: 5
b: 10
-----------------------------------------------------------------------------------------
fruits = ["apple", "mango", "orange"] #list
numbers = (1, 2, 3) #tuple
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels = {'a', 'e', 'i' , 'o', 'u'} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
['apple', 'mango', 'orange']
(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}
We can even convert one sequence to another.
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
-----------------------------------------------------------------------------------------
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'
-----------------------------------------------------------------------------------------
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
x = True
y = False
# Output: x and y is False
print('x and y is',x and y)
# Output: x or y is True
print('x or y is',x or y)
# Output: not x is False
print('not x is',not x)
-----------------------------------------------------------------------------------------
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)
-----------------------------------------------------------------------------------------
Assignment operators
Operator Example Equivatent to
= x = 5 x = 5
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x = x & 5
|= x |= 5 x = x | 5
^= x ^= 5 x = x ^ 5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
-----------------------------------------------------------------------------------------
Python Recursive Function
We know that in Python, a function can call other functions.
It is even possible for the function to call itself. These type of construct are termed as recursive functions.
# An example of a recursive function to
# find the factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
FLOW:
calc_factorial(4) # 1st call with 4
4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
4 * 3 * 2 # return from 3rd call
4 * 6 # return from 2nd call
24 # return from 1st call
-----------------------------------------------------------------------------------------
Python Anonymous/Lambda Function
In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Syntax of Lambda Function in python
lambda arguments: expression
Example:1
double = lambda x: x * 2
# Output: 10
print(double(5))
Example:2 //filter
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
# Output: [4, 6, 8, 12]
print(new_list)
Example:3 //map
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)
-----------------------------------------------------------------------------------------
import math
# Output: 3.141592653589793
print(math.pi)
# Output: -1.0
print(math.cos(math.pi))
# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))
# Output: 1.1752011936438014
print(math.sinh(1))
# Output: 720
print(math.factorial(6))
-----------------------------------------------------------------------------------------
import random
# Output: 16
print(random.randrange(10,20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
print(random.random())
-----------------------------------------------------------------------------------------
LIST:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
-|
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
-|
# mistake values
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
-|
We can add one item to a list using append() method or add several items using extend() method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)
-|
We can also use + operator to combine two lists
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
-|
The * operator repeats a list for the given number of times.
#Output: ["re", "re", "re"]
print(["re"] * 3)
-|
Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
-|
How to delete or remove elements from a list?
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
# delete multiple items
del my_list[1:5]
# Output: ['p', 'm']
print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)
-|
# remove() method to remove the given item
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# pop(i) method to remove an item at the given index.
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# pop() method removes and returns the last item if index is not provided.
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
clear() method to empty a list.
my_list.clear()
# Output: []
print(my_list)
delete items in a list by assigning an empty list to a slice of elements.
>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']
-|
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
my_list = [3, 8, 1, 6, 0, 8, 4]
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
-|
List Comprehension: Elegant way to create new List
pow2 = [2 ** x for x in range(10)]
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
same as
pow2 = []
for x in range(10):
pow2.append(2 ** x)
-|
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']
-|
my_list = ['p','r','o','b','l','e','m']
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
-----------------------------------------------------------------------------------------
Tuple: >> imutable list
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple) # Output: (1, "Hello", 3.4)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# Output: 3, 4.6, "dog"
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
-|
Creating a tuple with one element is a bit tricky.
my_tuple = ("hello") //creates a String
print(type(my_tuple)) # <class 'str'>
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
-|
Indexing:
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# IndexError: list index out of range
# print(my_tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
-|
Changing a Tuple (elements like List in Tuple can be changed)
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, item of mutable element can be changed
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
-|
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
-|
# Delete
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
-|
Method Description
count(x) Returns the number of items x
index(x) Returns the index of the first item that is equal to x
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
Comments
Post a Comment