Table of Contents
What’s the difference between raw_input() and input() in python?
In python 3.x raw_input()
was renamed to input()
. That is, the new input()
function reads a line from sys.stdin
and returns it with the trailing newline stripped. It raises EOFError
if the input is terminated prematurely. To get the old behavior of input()
, use eval(input())
.
In python 3.x input behave same as python 2.x raw_input
name = input('Enter Your name')
#entered value is Singhak
print(type(name)) # <class 'str'>
print(name) #Singhak
In python 2.x input behave different
age= input("Enter the age: ")
# Enter value is 28
print(type(age)) <class 'int'>
print(age) # 28
In Python 3.x, the input function explicitly converts the input you give to type string. But Python 2.x input function takes the value and type of the input you enter as it is without modifying the type.
The
raw_input()
function is similar toinput()
function in Python 3.x. Developers are recommended to use raw_input function in Python 2.x.
What is the difference between Xrange and range?
In python 2.x range()
returns a list and xrange()
returns an xrange object, which is kind of like an iterator and generates the numbers on demand.
In python 3.x range()
now behaves like xrange()
used to behave, except it works with values of arbitrary size. The latter no longer exists.
print(list(range(4))) #[0, 1, 2, 3]
print(range(4)) # range(0, 4)
What do you mean by list comprehension?
List comprehension is an elegant way to define and create lists based on existing lists. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
#Syntax
[expression for item in list]
lst = [x**2 for x in range(5)]
print(lst) # [0, 1, 4, 9, 16]
number_list = [ x for x in range(11) if x % 2 == 0]
print(number_list) # [0, 2, 4, 6, 8, 10]
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(obj) #['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
How we can write ternary operator in python?
Ternary operator syntax in python is not same as other language. In python it is different for other.
#Syntax
[on_true] if [expression] else [on_false]
If condition
evaluates to True
, then on_true
is evaluated and returned but on_false
is ignored, or else when on_false
is evaluated and returned but on_true
is ignored.
'true' if True else 'false' #'true'
'true' if False else 'false' #'false'
'Even' if 12%2 == 0 else 'Odd' #'Even'
#it is similar to
if 12%2==0 and 'Even' or 'Odd' # 'Even'
How can you remove duplicate element from a list?
We can remove duplicate elements from list using Set or list comprehension and many other ways.
dup_list = [2,4,5,3,2,7,8,4]
non_dup_list = list(set(dup_list))
print(non_dup_list) #[2,4,5,3,7]
#2nd method
non_dup = []
[non_dup.append(x) for x in dup_list if x not in non_dup]
print(non_dup) #[2,4,5,3,7]
What is the difference between / and // operator in Python?
"//"
operator give the floor value of division.
#//
print(1//2) #0
print(3//2) #1
print(4.0//3) # 1.0
print(4//2) # 2
"/"
operator give complete result of division means if result comes with decimal value it will not round off the result.
# /
print(1/2) #0.5
print(3/2) #1.5
print(4.0/3) # 1.3333333333333333
print(4/2) # 2.0
How is string interpolation performed?
We can do string interpolation with three ways.
f-strings
%-formatting
Str.format()
- f-strings
# 1.
name = 'Singhak'
age = 1.3
f"My name is {name} and age is {age}" # 'My name is Singhak and age is 1.3'
#2.
f"{2 * 37}" # "74"
#3.
f"{name.lower()} is Best." # singhak is Best.
#4.
F"Hello, {name}. You are {age}." # "Hello Singhak. You are 1.3"
- %-formatting
# 1.
name = 'Singhak'
age = 1.3
"Hello, %s. You are %.2f." % (name, age) # 'Hello, Singhak. You are 1.30.'
# 2.
"Hello, %s. You are is %.2f %s." % (name, age, name) # 'Hello, Singhak. You are is 1.30 Singhak.'
- str.format()
name = 'Singhak'
age = 1.3
person = {'name': 'Singhak', 'age': 14}
#1.
"Hello, {}. You are {}.".format(name, age) # 'Hello, Singhak. You are 1.3.'
# 2.
"Hello, {0}. You are is {1} {0}.".format(name, age, name) # 'Hello, Singhak. You are is 1.30 Singhak.'
# 3.
"Hello, {name}. You are {age}.".format(**person) # 'Hello, Singhak. You are 14.'
#4.
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age']) # 'Hello, Singhak. You are 14.'
How the reduce function works?
reduce
takes a function and a sequence and iterates over that sequence. On each iteration, both the current element of sequence and output from the previous element are passed to the function. At the end of itration, a single value is returned.
from functools import reduce
def add(x,y):
return x + y
lst = [34,56,23,78,90]
reduce(add, lst) # 258
How do any() and all() work?
any
takes a sequence and returns true if any element in the sequence is true.
If the iterable object is empty, the
any()
function will return False.
all
returns true only if all elements in the sequence are true.
a = [False, False, False]
b = [True, False, False]
c = [True, True, True]
print( any(a) ) # False
print( any(b) ) # True
print( any(c) ) # True
print( all(a) ) # False
print( all(b) ) # False
print( all(c) ) # True
any and all with dictionaries.
# 0 is False
d = {0: 'False'}
print(any(d)) # False
# 1 is True
d = {0: 'False', 1: 'True'}
print(any(d)) # True
########## all
s = {0: 'False', 1: 'False'}
print(all(s)) #False
s = {1: 'True', 2: 'True'}
print(all(s)) # True
s = {1: 'True', False: 0}
print(all(s)) # False
When used on a dictionary, the any() or all() function checks if any of the keys are true, not the values.
How is exception handling performed in Python?
Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors. We can handle these built-in and user-defined exceptions in Python using try
, except
and finally
statements.
#Syntax 1
try:
# try to do this
except:
# if try block fails then do this
finally:
# always do this
#Syntax 2
try:
# try to do this
finally:
# always do this
#Syntax 3
try:
# try to do this
except:
# if try block fails then do this
else:
# if the code block inside try ran without any errors
How can access the index in ‘for’ loops?
We can use built-in function enumerate()
, available in both Python 2 and 3. enumerate()
give us both value and index.
#syntax
enumerate(iterable, start=0)
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
print(type(enumerateGrocery))
# converting to list
print(list(enumerateGrocery))
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))
#outputs
<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]
grocery = ['bread', 'milk', 'butter']
for item in enumerate(grocery):
print(item)
print('\n')
for count, item in enumerate(grocery):
print(count, item)
#outputs
(0, 'bread')
(1, 'milk')
(2, 'butter')
0 bread
1 milk
2 butter
By default index in enumerate() start with 0, we can change it any starting point.
print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)
#output
100 bread
101 milk
102 butter
How to combine two lists into a list of tuples?
We can use zip()
function to combine two or more list and generate list of tuples.
#syntax
zip(*iterables)
number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']
print(list(zip(number_list, str_list)))
# [(2, 'two'), (3, 'three'), (1, 'one')]
Zip two different size of list
str_list = ['one', 'two']
numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR')
print(list(zip(str_list, numbers_tuple)))
#[('one', 'ONE'), ('two', 'TWO')]
How to check if a value exists in a list or not?
We can use in
operator to check any value exist in list or not.
"a" in ["a","b","d","2"]
# True
2 in ["a","b","d","2"]
#False
What is the difference between deep and shallow copy?
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.