Here are the top Python interview questions and answers that cover a wide basic level topics associated with Python such as pickling and unpickling, slicing, basic types of functions available in Python, ways to convert a string to a number in Python, whitespaces in Python and advanced level topics like iterators, generators, decorators, rstrip() function in Python. Go through these Python interview question-answer sets and land your dream job as a Python Developer, Full Stack engineer, and other top profiles. Practice these interview questions on Python with answers provided by experts and be fully prepared for your next Python interview.
Some of the features of Python are -
Pickling can be used in Python to pickle an object so that it can be saved on disk. Basically, pickling is a process to convert a python object (list, dict, etc.) into a character stream using a pickle module. Pickling “serialises” the object first before it writes it to file.
There are two types of pickling method -
On the other hand, unpickling is the reverse process. It retrieves the stored string and converts it back into an object.
Slicing in Python is a process that can be used to select a range of items from Sequence types such as strings, list, tuple and so on.
The slice() constructor simply creates a slice object representing the set of indices specified by range(start, stop, step).
In Python, slice() accepts three parameters which means the same in both constructs:
Suppose, a single parameter is passed then, start and step are set to None.
For example - To create a slice object for slicing
# contains indices (0, 1, 2) print(slice(3)) # contains indices (1, 3) print(slice(1, 5, 2)
After you run the program, you will get the following output.
slice(None, 3, None) slice(1, 5, 2)
This is how a generator function differs from a normal function.
Python is an object-oriented programming language. OOP concept means that we can solve a problem in Python by creating an object model in our program. Some of the features of object-oriented programming are inheritance, polymorphism, abstraction, encapsulation.
Python uses range() function which generates a list of numbers and is used to iterate over loops.
for i in range(5): print(i)
The two set of parameters are accompanied by the range() function.
print sum(range(10,101)) #range() returns a list to the sum function containing #all the numbers from 10 to 100. Please see that #the range function does not include the end given (101 here). print(sum(xrange(10, 101))) #xrange() returns an iterator rather than a list #which is less heavy in the memory.
Python provides us with two basic types of functions:
PEP stands for Python Enhancement Proposal. It is mainly used to maintain specific standards. PEP 8 is one of Python’s style guide and it is a set of rules which are followed to format Python code for maximum readability. Writing code using specific standards helps us to make large code bases, as well as other coders, can contribute to it easily and it turns out to be uniform too.
The <int()> method provided by Python, is a standard built-in function which converts a string into an integer value.
It can be called with a string containing a number as the argument, and it will return the number converted to an actual integer.
print int("1") + 2 The above prints 3.
The most commonly used built-in types which Python support are -
In Python, whitespaces are the character used for spacing and separation. It has an ‘empty’ representation. In the context of Python, whitespace can be a tab or space.
The whitespace characters can be used interchangeably to separate tokens except at the beginning of a logical line or in string literals. Whitespace is a must between two tokens if there is concatenation else it can be interpreted as a different token. For example, “ab” is one token whereas “a b” are two tokens.
A function in Python can be created in the steps mentioned below:
Step 1: To start with the function, declare the function by writing the keyboard def followed by the function name.
Step 2: Now write the arguments inside the open and close parentheses of the function, and end the declaration with a colon.
Step 3: Next, add the program statements which needs to be executed.
In Python, when the argument whether a value or an expression gets bound to a respective variable in the function it is said to be “Call by Value”.
Python treats that variable as local and any changes made to that variable remains local and does not reflect outside the function.
In Python, both “call by reference” and “pass by reference” are used interchangeably. When an argument is passed by reference, it is then available as an implicit reference to the function instead of a simple copy. If any modification is made to the argument, it will also be visible to the caller.
The advantage of this is that it brings in more time and space efficiency there is no need to create local copies.
On the other hand, the disadvantage is there could be a situation when a variable gets changed accidentally during a function call. To avoid such cases, the programmer needs to look into the code.
In Python, the default print() function ends with a newline. The print() function comes with a parameter called ‘end’ and the value of this parameter in ‘/n’ which means a new line. A print statement can be ended with any character/string using this parameter. Using this parameter, we can change the end character in the print statement according to our choice.
For example, in print a line instead of the new line in the end:
print("Let us learn" , end = ' ') print("Python") # Printing a dot in the end. print("knowledgehut" , end = '.') print("com", end = ' ')
The output is
Let us learn Python
knowledgehut.com
In Python, there are two types of errors - syntax error and exceptions.
Syntax Error- It is also known as parsing errors. Errors are issues in a program which may cause it to exit abnormally. When an error is detected, the parser repeats the offending line and then displays an arrow which points at the earliest point in the line.
Exceptions- Exceptions take place in a program when the normal flow of the program is interrupted due to the occurrence of an external event. Even if the syntax of the program is correct, there are chances of detecting an error during execution, this error is nothing but an exception. Some of the examples of exceptions are - ZeroDivisionError, TypeError and NameError.
The key difference between lists and tuples is the fact that lists have mutable nature and tuples have immutable nature.
It is said to be a mutable data type when a python object can be modified. On the other hand, immutable data types cannot be modified. Let us see an example to modify an item list vs tuple.
list_num[2] = 5 print(list_num) tup_num[2] = 5
Output:
[1,2,5,4] Traceback (most recent call last): File "python", line 6, in <module> TypeError: 'tuple' object does not support item assignment
In this code, we had assigned 5 to list_num at index 2 and in the output, we can see 5 is found in index 2. However, we had assigned 5 to tup_num at index 2 but we got type error on the output. This is because we cannot modify tuples due to its immutable nature.
A module is a Python object which contains an arbitrarily named ‘attributes’ that you can bind. Python modules are basically files which contain Python codes. This code can define variables, functions or classes. It allows you to organize your Python code logically. It can also include runnable code.
Some of the commonly used built-in modules in Python are:
Global Variables - The variables which are declared outside a function are called global variables. Such variables can be accessed by any function in the program.
Local Variables - The variables which are declared inside a function are known as local variables and such variables are present in the local space and not in the global space.
For example:
a=4 #global variable def add(): b=6 #local variable c=a+b print c add()
Output:
10
In Python, type conversion is used to directly convert one data type to another. Some of the data types are mentioned below:
int() | It converts any data type into integer type |
float() | It converts any data type into float type |
ord() | It converts characters into an integer |
hex() | It converts integers to hexadecimal |
oct() | It converts an integer to octal |
tuple() | It is used to convert to a tuple |
set() | It is used to return the type after converting to set |
list() | It is used to convert any data type to a list type |
dict() | It is is used to convert a tuple of order (key, value) into a dictionary |
str() | It is used to convert an integer into a string |
complex(real,imag) | It converts real numbers to complex(real,imag) number |
Indentation is important in Python. It indicates a block of code. Anything within loops, functions or classes etc. is specified within an indented block. Indentation is generally done using four space characters, if the code is not properly indented, the execution will not be accurate and will also show errors.
Numpy Arrays | Lists |
---|---|
NumPy is more efficient and more convenient. A lot of vector and matrix operations are available and they can be efficiently implemented. | Lists in Python are efficient general purpose containers. It supports efficient insertion, deletion, concatenation and appending. Lists make it easier to construct and manipulate. |
NumPy is fast and a lot of built-in functions are available such as FFTs, convolutions, statistics, linear algebra, histogram etc. | Lists have certain limitations as they do not support “vectorized” operations such as element-wise addition and multiplication and also the fact that it contains different types of objects |
The main difference between Pass and Continue is that the continue statement allows the loop to resume from the next iteration. On the other hand, the pass statement does nothing and the remaining code is executed as usual.
An index in Python is an integer data type which basically denotes a position within an ordered list or a string. In Python, strings are considered as a list of characters and we can get access to each character using the index which begins from zero and ends with the length minus one.
In Python, the len() function is used to determine the length of an input string. It is a primary string function which can be used to calculate the number of characters present in a string.
For example,
str_name = 'learning'
len(str_name)
The output will be -
8
In Python, comments are written using the # character. Alternatively, comments can be written using docstrings (strings enclosed with triple quotes).
For example:
#Comments in Python starts with the hash character
print("Comments in a Python code start with a #")
Output:
Comments in a Python code start with a #
In Python, a lambda function is an anonymous function which can have any number of parameters but should contain only one statement.
For example:
a = lambda x,y : x+y print(a(3, 9))
Output:
12
In order to convert a string to lowercase, the function lower() can be used.
For example:
str_name='LEARN'
print(str_name.lower())
Output:
learn
In Python, docstrings are not really comments but are documentation strings. They can be used as comments. It is denoted within triple quotes. Docstrings are not assigned to any variable and therefore serves the purpose of comments as well
For example:
""" Using docstring as a comment. This code divides 2 numbers """ x=12 y=3 z=x/y print(z)
Output:
4.0
In Python, a dictionary is a built-in datatype. It defines a one-to-one relationship between keys and values. Each pair of keys have their corresponding values. They are indexed by keys.
For example,
Consider some key and value pairs such as Name, Age and Blood group (BG).
dict={'Name' : 'James', 'Age' : '25' : 'BG' : 'A+'} print dict[name]
James
print dict[Age]
25
print dict[BG]
A+
Firstly, import OS module and then use os.remove() function in order to delete files in Python.
For example:
import os os.remove("file_name.txt")
The main differences between lambda and def are mentioned below -
Lambda | Def |
---|---|
It is a uni-expression function. | It can hold multiple expressions. |
It forms a function object and returns it. | It generates a function and designates a name to call it. |
It cannot return statements. | It can have a return statement. |
It can be used inside a list and dictionary. | It does not support to get used. |
In Python, sequences are indexed with both positive and negative numbers. The positive numbers use ‘0’ as the first index and ‘1’ as the second index and so on.
Similarly, the index for the negative number starts from ‘-1’ which represents the last index in the sequence and ‘-2’ as the penultimate index and it goes on just like the positive numbers.
The negative index helps in the removal of the new-line spaces from the string and it can also be used to show the index to represent the string in the correct order.
Encapsulation is the process of binding the code and the data together. An example of encapsulation would be a Python class.
Python does not support multiple inheritances as Java does. Multiple inheritances mean that from more than one parent classes a class can be derived.
Polymorphism is the ability to take multiple forms. Suppose if the parent class has a method named XYZ then the child class can have the same name with its own variables and parameters. Python supports polymorphism.
Data Abstraction allows you to provide only the required details and hides the implementation from the world. It can be easily achieved in Python by using interfaces and abstract classes.
Python lays down a convention of prefixing the name of the method/variable with a single or double underscore to emulate the behaviour of protected and private access specifiers. All the members in a Python class are public by default. Also, any member can be accessed from outside the class environment.
In Python, the class keyword is used to create a class.
For example:
class Stduent: def __init__(self, name): self.name = name S1=Student("Steve") print(E=S1.name)
Output:
Steve
An object() returns a featureless object which is a base for all classes. It does not consider any parameters.
In order to reverse a list, use list.reverse() − it reverses objects of the list in place. The reverse() function doesn't return any value. The elements are reversed and the lists are updated.
# Operating System List os = ['Windows', 'macOS', 'Linux'] print('Original List:', os) # List Reverse os.reverse() # updated list print('Updated List:', os)
Output:
Original List: ['Windows', 'macOS', 'Linux'] Updated List: ['Linux', 'macOS', 'Windows']
NumPy is a Python library which is written in C and therefore is one of the fastest and most compatible libraries among the rest. It is a basic library for mathematical or numerical calculation. Some of the basic operations are indexing, reshaping, indexing etc..
On the other hand, SciPy stands for scientific Python and has been written on the top of NumPy. Some of the operations include: Special functions (scipy.special), Integration (scipy.integrate), Optimization (scipy.optimize), Interpolation (scipy.interpolate), Fourier Transforms (scipy.fftpack), Signal Processing (scipy.signal), Linear Algebra (scipy.linalg), Statistics (scipy.stats).
Python supports:
‘+’ : Addition
‘-’ : Subtraction
‘*’ : Multiplication
‘/’ : Division
‘%’ : Modulo division
‘**’ : Power Of
‘//’ : floor div
Python also supports augmented assignment operators such as -
A += 5 means A = A + 5
B -= 7 means B = B - 7
Some other operators Python support are & , |, ~ , ^ which are and, or, bitwise complement and bitwise xor operations.
Python does not support unary operators such as ++ or - operators.
Python allows us to handle loops in an interesting manner by providing a function to write else block for cases when the loop does not satisfy a certain condition.
For example :
x = [ ] for i in x: print "in for loop" else: print "in else block"
Output:
in else block
It works in a similar manner with while-else.
In Python, the tuple() function can be used to convert a list into a tuple. As tuples are immutable, we cannot change it back to a list.
For example:
days = ['sun','mon','tue','wed','thu','fri','sat']
listtoTuple = tuple(days)
print(listtoTuple)
Output:
('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
In Python, set() function can be used to convert a list into a set.
For example:
days = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listtoSet = set(days)
print(listtoSet)
Output:
set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
In the Python list, we can use the count() function to count the occurrences of an individual element.
Example # 1:
days = ['sun','mon','tue','wed','thu','fri','sun','tue','tue', 'tue'] print(days.count('tue'))
Output:
4
Example # 2:
days = ['sun','mon','tue','wed','thu','fri','sun','tue','tue'] print([[x,days.count(x)] for x in set(days)])
Output:
[['wed', 1], ['sun', 2], ['thu', 1], ['tue', 3], ['mon', 1], ['fri', 1]]
Some of the most used text processing methods are mentioned below:
a = 'hello world' a.upper() #Converts to Uppercase 'HELLO WORLD' a.lower() #Converts to Lowercase 'hello world' a.capitalize() #First Letter is capitalized. 'Hello world' a.title() #First character of the every word is capitalized. 'Hello World' a.split() #Splits based on space and returns a list. Split takes an optional parameter to split. By #default it considers space based on which it splits ['hello', 'world'] record = 'name:age:id:salary' #Splitting based on ':' record.split(':') ['name', 'age', 'id', 'salary'] a = '\n\t hello world \t\n' print a hello world a.strip() #strips leading and trailing white spaces and newlines. 'hello world' a.lstrip() #left strip 'hello world \t\n' a.rstrip() #right strip '\n\t\thello world' a = 'hello' a.isalpha() #returns true only if the string contains alphabets. True a = 'hello world' #As there is a space, it returned false. a.isalpha() False a = '1234' >> a.isdigit() #Returns True only if the string contains digits. True a = '1234a' a.isdigit() #returned false as the string contains a alphabet False a.isalnum() # returns true if the string contains alphabets and digits. True a = 'Name: {name}, Age: {age}' a.format(name='Harry', age='22') 'Name: Harry, Age: 22'
In python, we have a method called update() which can be used in order to merge one dictionary on another.
For example:
a = {'a':3} b = {'b':2} a.update(b) a
Output:
{'a': 3, 'b': 2}
In Python, all functions and variables follow lowercase and underscore naming convention. For example,
is_prime(), test_var = 30 etc.
However, constants are either camelcase or uppercase. For example,
Max_val = 20, PI = 3.14
Even for class names, camelcase is followed. For example,
UserNames
In Python, the sys module gives the version of Python being used. The code mentioned below shows how to check for the version.
import sys
print(sys.version)
In order to get the list of all the keys in a dictionary, use function keys(). For example,
mydict={'a':1,'b':2,'c':3,'e':5} mydict.keys() dict_keys(['a', 'b', 'c', 'e'])
def f(x,l=[]): for i in range(x): l.append(i*i) print(l) f(2) f(3,[3,2,1]) f(3)
The output will be:
[0, 1] [3, 2, 1, 0, 1, 4] [0, 1, 0, 1, 4]
Some of the additional data structures are -
The code mentioned below can be used to save an image locally from an URL address.
import urllib.request urllib.request.urlretrieve("URL", "local-filename.jpg")
Random numbers can be generated by using various functions in Python. They are -
In Python, to find the type and identification number of an object, we can use the functions type() and id().
type(<variableName>) - It gives us the type of the object that variable is pointing to.
id(<variablename>) - It gives us the unique identification number of the object that variable is pointing to.
In Python, an iterator is an object which can be iterated upon. It is an object which will return data, only one element at a time. Python iterator should implement two special methods, __iter__() and __next__(), which are collectively known as iterator protocol.
Most of the built-in containers in Python such as list, tuples, string etc. are iterables and an object is called iterable only if we can get an iterator from it. The iter() function returns an iterator from them.
mytuple = ("alice", "bob", "charlie") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))o
alice bob charlie
In Python, a generator is a type of function which allows us to specify a function which acts as an iterator and therefore can be used in a ‘for’ loop. In a generator function, the yield keyword replaces the return statement.
# Simple Python function def fn(): return "Simple Python function." # Python Generator function def generate(): yield "It is a PG function." print(next(generate()))
The output is:
It is a PG function.
In Python, decorator allows us to add new behaviour to the given objects dynamically. In the example below, a simple program shows how to display a message pre and post the execution of a function.
def deco_sample(func): def deco_hook(*args, **kwargs): print("Before the function is called") result = func(*args, **kwargs) print("After the function is called") return result return deco_hook @deco_sample def product(x, y): "Function to multiply two numbers." return x * y print(product(6, 6))
The output is:
Before the function is called
After the function is called
36
In Python, we can use two approaches in order to copy an object, Shallow Copy and Deep Copy.
Shallow Copy- In this approach, a new object is created which stores the reference of the original elements. A shallow copy simply copies the reference of nested objects and do not create a copy of nested objects.
For example,
import copy list_old = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] list_new = copy.copy(list_old) print("Old list:", list_old) print("New list:", list_new)
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Deep Copy- In this approach, a new object is created and it recursively adds the copies of nested objects which are present in the original elements. In the example below, we will create a deep copy using deepcopy() function which is present in the copy module.
For example,
import copy list_old = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] list_new = copy.deepcopy(old_list) print("Old list:", list_old) print("New list:", list_new)
Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]] New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
The main() function is said to be the entry point of a program, which is called first in most of the programming languages. In Python, the interpreter first executes the source file code in a sequential manner and do not call any method if it isn’t part of the code. However, if it is directly a part of the code then it is executed while the file is imported as a module.
To define this main method, there is a special technique used so that it is executed only when the program is run directly and not when it is imported as a module. A simple example mentioned below shows how to define python main function.
print("Hello") print("__name__ value: ", __name__) def main(): print("Print the main function") if __name__ == '__main__': main()
The output:
Hello __name__ value: __main__ Print the main function
In Python, the rstrip() function can be used to duplicate the string but it leaves out the whitespace characters from the end. This function excludes the characters from the right end as per the argument value i.e, a string mentioning the group of characters to get excluded.
The signature of the rstrip() is:
str.rstrip([char sequence/pre>
For example,
str_name = 'Python'
#The white spaces are excluded
print(str_name.rstrip())
To handle Exceptions, Python provides constructs such as Try, Except, Finally. The unsafe code is indented under the Try block and then the fall-back code is kept inside the Except block. Lastly, any kind of instructions intended for execution comes under the Finally block.
try: print("Executing code in the try block") print(exception) except: print("Entering in the except block") finally: print("Reached the final block")
The output is:
Executing code in the try block Entering in the except block Reached the final block
In Python, globals() function returns the current global symbol table as a dictionary object. To keep all necessary information about a program, python maintains a symbol table. The information in this table remains in the global scope of the program and we can retrieve it by using the globals() method.
For example:
x = 8 def fn(): y = 7 z = y + x # Calling the globals() method z = globals()['x'] = z return z # Test Code ret = fn() print(ret)
The output is:
15
In Python, closures are function objects which are returned by another function. It is used to eliminate code redundancy.
In the example below, it shows a simple closure for multiplying numbers
def multiply_number(num): def product(number): 'product() here is a closure' return num * number return product num_2 = multiply_number(3) print(num_2(11)) print(num_2(30)) num_6 = multiply_number(6) print(num_6(1))
The output is:
33
90
6
The pass statement is the statement which is a null operation. No operations take place when the pass statement is executed. It results in no operation (NOP). Python statements are case sensitive, so you should always write “pass” in lowercase, if you write “Pass”, an error will be shown: “NameError: name Pass is not defined.”
For example,
# pass is just a placeholder for # functionality to be added later. sequence = {'p', 'a', 's', 's'} for val in sequence: pass
The optional statements that can be used in the try-except block are-
It is used if you would like to run a piece of code when the try block does not create an exception.
It is used when you would like to execute some steps which run irrespective of whether an exception occurs or not.
*args is used as a parameter in the function header. It allows us to pass N (variable) number of arguments. However, it does not allow passing a named argument to the function.
For example, let us see a python code to demonstrate *args for dynamic arguments.
def fn(*argList): for argx in argList: print (argx) fn('Let', 'Us', 'Learn', 'Python')
The output:
Let Us Learn Python
The split() function can be used to separate large strings into smaller ones or rather sub-strings. We can either use a separator for the split else it will use the space as one by default.
For example,
str_name = 'alice bob charlie' str_name.split(" ") str_name.split()
The output will be -
['alice', 'bob', 'charlie'] ['alice', 'bob', 'charlie']
title() method can be used to convert the first letter in each word to capital (uppercase) and the rest turns to lowercase.
For example,
str_name = 'cOnTInuOus lEarnIng'
str_name.title()
The output will be -
Continuous Learning
Iterable is a type of object which would generate an Iterator when passed to in-built method iter()
For an object to be iterable, the class of the object needs to define two instance methods: __len__ and __getitem__. Such an object, when passed to method iter(), would generate an iterator.
Iterator is the object which is used to iterate over an iterable object. It provides __next__ method to do so. The __next__ method is implicitly called when we use it in for loop.
In Python, lists and arrays store data in a similar manner. However, arrays hold only single data type elements whereas lists can hold any data type elements.
For example:
import array as arr My_Array=arr.array('i',[1,2,3,4]) My_list=[1,'abc',1.20] print(My_Array) print(My_list)
Output:
array('i', [1, 2, 3, 4]) [1, 'abc', 1.2]
In order to reverse the order of an array we can use [::-1]
For example:
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])
Operators are considered to be special functions. They accept one or more than one values and produce a corresponding result.
is: It returns true when 2 operands are true (Example: “a” is ‘a’)
not: It returns the inverse of the boolean value.
in: It checks if some element is present in some sequence
Both the functions, help() and dir() can be accessed from the Python interpreter and is used to view a consolidated dump of built-in functions.
help() function - It is used to display the documentation string and it also facilitates you to check the help related to keywords, modules or attributes etc..
dir() function - It is used to display the defined symbols.
In order to add values or elements you can use functions like append(), extend() and the insert (i,x).
For example:
a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.append(3.4) print(a) a.extend([4.5,6.3,6.8]) print(a) a.insert(2,3.8) print(a)
Output:
array('d', [1.1, 2.1, 3.1, 3.4]) array('d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8]) array('d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])
In order to remove values or elements, we can use pop() and remove() methods. The main difference between these two functions is that pop() function returns the deleted value and remove() function do not.
For example:
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6]) print(a.pop()) print(a.pop(3)) a.remove(1.1) print(a)
Output:
4.6 3.1 array('d', [2.2, 3.8, 3.7, 1.2])
We can calculate percentiles with the following code
import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p)
Output:
3
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) A1 = range(10)A2 = sorted([i for i in A1 if i in A0]) A3 = sorted([A0[s] for s in A0]) A4 = [i for i in A1 if i in A3] A5 = {i:i*i for i in A1} A6 = [[i,i*i] for i in A1] print(A0,A1,A2,A3,A4,A5,A6)
The following will be the final outputs of A0, A1, … A6
A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary A1 = range(0, 10) A2 = [] A3 = [1, 2, 3, 4, 5] A4 = [1, 2, 3, 4, 5] A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
To get the indices of N maximum values in a NumPy array you can use the below code:
import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1])
Output:
[ 4 3 1 ]
In order to sort a list in Python, the following code can be used :
list = ["1", "4", "0", "6", "9"] list = [int(i) for i in list] list.sort() print (list)
a=input("enter a sequence") b=a[::-1] if a==b: print("palindrome") else: print("Not a Palindrome")
Output:
enter a sequence 656 palindrome
a=int(input("enter a number")) if a>1: for x in range(2,a): if(a%x)==0: print("not prime") break else: print("Prime") else: print("not prime") for x in range(2,a): if(a%x)==0: print("not prime")
Output:
enter a number 3 Prime
# Enter number of terms needed #0,1,1,2,3,5.... a=int(input("Enter the terms")) f=0 #first element of series s=1 #second element of series if a<=0: print("The requested series is\n",f) else: print(f,s,end=" ") for x in range(2,a): next=f+s print(next,end=" ") f=s s=next
Output:
Enter the terms 5 0 1 1 2 3
def bs(a): # a = name of list b=len(a)-1 # minus 1 because we always compare 2 adjacent values #number of rounds will be 1 less than the total length of the list for x in range(b): for y in range(b-x): if a[y]>a[y+1]: a[y],a[y+1]=a[y+1],a[y] return a a=[46,3,5,4,2,68,92] bs(a)
Output:
[2, 3, 4, 5, 46, 68, 92]
def list_sum(list_num): if len(list_num) == 1: return list_num[0] else: return list_num[0] + list_sum(list_num[1:]) print(list_sum([3, 8, 2, 4, 5]))
Output:
22
A class which do not have any code defines within its block is known as an empty class. An empty class can be created using a pass keyword. However, objects can be created outside the class itself.
For example-
class x: pass obj=x() obj.name="abc" print("Name = ",obj.name)
Output:
Name = abc
In Python, memory management involves a private heap of Python objects and data structures. The interpreter takes control of Python heap and the developer does not have access to it.
Allocation of heap space for Python objects is assigned by the Python memory manager. There are certain tools provided by the core API of Python which helps to code reliable and more robust program.
Python has a built-in garbage collector, all the unused memory is recycled here. The GC module can be enabled and disabled by using defined functions-
gc.enable () - It enables the garbage collector for automatic garbage collection
gc.disable() - It disables the garbage collector for automatic garbage collection.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = (i for i in a if i%3 == 0) #Generator expression. for i in b: print i, 0 3 6 9
The term monkey patch refers to dynamically modifying a class or module at run-time. In Python, we change the behaviour of code at run-time. Let us look into an example to understand in a better way.
# monk.py class A: def func(self): print "Calling func()"
In the above code, we created a module and will be using later in order to change the behaviour of func() at run-time by assigning various values.
import monk def monkey_f(self): print "monkey_f() is being called" # replacing the address of "func" with "monkey_f" monk.A.func = monkey_f obj = monk.A() # calling function "func" whose address got replaced # with function "monkey_f()" obj.func()
Output:
monkey_f() is being called
A class is also called the child/derived/subclass inheriting from the parent/base/superclass when it inherits. It inherits all attributes and methods from another class.
Inheritance allows us to reuse our code and make it simpler to create and maintain applications. Python supports -
A higher order function returns a new function by accepting one or more functions as input. In order to make high order functions, we will have to first import functools module. Functions like functools.partial() is often used for high order function. The functions act on or else return the other functions. For this particular module, the callable object can be treated as a function.
Python libraries are a collection of Python packages. Some of the majorly used python libraries are –Numpy, Pandas, Matplotlib, Scikit-learn and many more.
In Python, we can use other numbering systems apart from decimal such as binary, octal, and hexadecimal.
In Python, the enumerate() function is used to add a counter to an iterable object. enumerate() function accepts sequential indexes starting from zero.
For example,
subjects = ('Python', 'Java', 'C++') for i, subject in enumerate(subjects): print(i, subject)
Output:
0 Python 1 Java 2 C++
Some of the features of Python are -
Pickling can be used in Python to pickle an object so that it can be saved on disk. Basically, pickling is a process to convert a python object (list, dict, etc.) into a character stream using a pickle module. Pickling “serialises” the object first before it writes it to file.
There are two types of pickling method -
On the other hand, unpickling is the reverse process. It retrieves the stored string and converts it back into an object.
Slicing in Python is a process that can be used to select a range of items from Sequence types such as strings, list, tuple and so on.
The slice() constructor simply creates a slice object representing the set of indices specified by range(start, stop, step).
In Python, slice() accepts three parameters which means the same in both constructs:
Suppose, a single parameter is passed then, start and step are set to None.
For example - To create a slice object for slicing
# contains indices (0, 1, 2) print(slice(3)) # contains indices (1, 3) print(slice(1, 5, 2)
After you run the program, you will get the following output.
slice(None, 3, None) slice(1, 5, 2)
This is how a generator function differs from a normal function.
Python is an object-oriented programming language. OOP concept means that we can solve a problem in Python by creating an object model in our program. Some of the features of object-oriented programming are inheritance, polymorphism, abstraction, encapsulation.
Python uses range() function which generates a list of numbers and is used to iterate over loops.
for i in range(5): print(i)
The two set of parameters are accompanied by the range() function.
print sum(range(10,101)) #range() returns a list to the sum function containing #all the numbers from 10 to 100. Please see that #the range function does not include the end given (101 here). print(sum(xrange(10, 101))) #xrange() returns an iterator rather than a list #which is less heavy in the memory.
Python provides us with two basic types of functions:
PEP stands for Python Enhancement Proposal. It is mainly used to maintain specific standards. PEP 8 is one of Python’s style guide and it is a set of rules which are followed to format Python code for maximum readability. Writing code using specific standards helps us to make large code bases, as well as other coders, can contribute to it easily and it turns out to be uniform too.
The <int()> method provided by Python, is a standard built-in function which converts a string into an integer value.
It can be called with a string containing a number as the argument, and it will return the number converted to an actual integer.
print int("1") + 2 The above prints 3.
The most commonly used built-in types which Python support are -
In Python, whitespaces are the character used for spacing and separation. It has an ‘empty’ representation. In the context of Python, whitespace can be a tab or space.
The whitespace characters can be used interchangeably to separate tokens except at the beginning of a logical line or in string literals. Whitespace is a must between two tokens if there is concatenation else it can be interpreted as a different token. For example, “ab” is one token whereas “a b” are two tokens.
A function in Python can be created in the steps mentioned below:
Step 1: To start with the function, declare the function by writing the keyboard def followed by the function name.
Step 2: Now write the arguments inside the open and close parentheses of the function, and end the declaration with a colon.
Step 3: Next, add the program statements which needs to be executed.
In Python, when the argument whether a value or an expression gets bound to a respective variable in the function it is said to be “Call by Value”.
Python treats that variable as local and any changes made to that variable remains local and does not reflect outside the function.
In Python, both “call by reference” and “pass by reference” are used interchangeably. When an argument is passed by reference, it is then available as an implicit reference to the function instead of a simple copy. If any modification is made to the argument, it will also be visible to the caller.
The advantage of this is that it brings in more time and space efficiency there is no need to create local copies.
On the other hand, the disadvantage is there could be a situation when a variable gets changed accidentally during a function call. To avoid such cases, the programmer needs to look into the code.
In Python, the default print() function ends with a newline. The print() function comes with a parameter called ‘end’ and the value of this parameter in ‘/n’ which means a new line. A print statement can be ended with any character/string using this parameter. Using this parameter, we can change the end character in the print statement according to our choice.
For example, in print a line instead of the new line in the end:
print("Let us learn" , end = ' ') print("Python") # Printing a dot in the end. print("knowledgehut" , end = '.') print("com", end = ' ')
The output is
Let us learn Python
knowledgehut.com
In Python, there are two types of errors - syntax error and exceptions.
Syntax Error- It is also known as parsing errors. Errors are issues in a program which may cause it to exit abnormally. When an error is detected, the parser repeats the offending line and then displays an arrow which points at the earliest point in the line.
Exceptions- Exceptions take place in a program when the normal flow of the program is interrupted due to the occurrence of an external event. Even if the syntax of the program is correct, there are chances of detecting an error during execution, this error is nothing but an exception. Some of the examples of exceptions are - ZeroDivisionError, TypeError and NameError.
The key difference between lists and tuples is the fact that lists have mutable nature and tuples have immutable nature.
It is said to be a mutable data type when a python object can be modified. On the other hand, immutable data types cannot be modified. Let us see an example to modify an item list vs tuple.
list_num[2] = 5 print(list_num) tup_num[2] = 5
Output:
[1,2,5,4] Traceback (most recent call last): File "python", line 6, in <module> TypeError: 'tuple' object does not support item assignment
In this code, we had assigned 5 to list_num at index 2 and in the output, we can see 5 is found in index 2. However, we had assigned 5 to tup_num at index 2 but we got type error on the output. This is because we cannot modify tuples due to its immutable nature.
A module is a Python object which contains an arbitrarily named ‘attributes’ that you can bind. Python modules are basically files which contain Python codes. This code can define variables, functions or classes. It allows you to organize your Python code logically. It can also include runnable code.
Some of the commonly used built-in modules in Python are:
Global Variables - The variables which are declared outside a function are called global variables. Such variables can be accessed by any function in the program.
Local Variables - The variables which are declared inside a function are known as local variables and such variables are present in the local space and not in the global space.
For example:
a=4 #global variable def add(): b=6 #local variable c=a+b print c add()
Output:
10
In Python, type conversion is used to directly convert one data type to another. Some of the data types are mentioned below:
int() | It converts any data type into integer type |
float() | It converts any data type into float type |
ord() | It converts characters into an integer |
hex() | It converts integers to hexadecimal |
oct() | It converts an integer to octal |
tuple() | It is used to convert to a tuple |
set() | It is used to return the type after converting to set |
list() | It is used to convert any data type to a list type |
dict() | It is is used to convert a tuple of order (key, value) into a dictionary |
str() | It is used to convert an integer into a string |
complex(real,imag) | It converts real numbers to complex(real,imag) number |
Indentation is important in Python. It indicates a block of code. Anything within loops, functions or classes etc. is specified within an indented block. Indentation is generally done using four space characters, if the code is not properly indented, the execution will not be accurate and will also show errors.
Numpy Arrays | Lists |
---|---|
NumPy is more efficient and more convenient. A lot of vector and matrix operations are available and they can be efficiently implemented. | Lists in Python are efficient general purpose containers. It supports efficient insertion, deletion, concatenation and appending. Lists make it easier to construct and manipulate. |
NumPy is fast and a lot of built-in functions are available such as FFTs, convolutions, statistics, linear algebra, histogram etc. | Lists have certain limitations as they do not support “vectorized” operations such as element-wise addition and multiplication and also the fact that it contains different types of objects |
The main difference between Pass and Continue is that the continue statement allows the loop to resume from the next iteration. On the other hand, the pass statement does nothing and the remaining code is executed as usual.
An index in Python is an integer data type which basically denotes a position within an ordered list or a string. In Python, strings are considered as a list of characters and we can get access to each character using the index which begins from zero and ends with the length minus one.
In Python, the len() function is used to determine the length of an input string. It is a primary string function which can be used to calculate the number of characters present in a string.
For example,
str_name = 'learning'
len(str_name)
The output will be -
8
In Python, comments are written using the # character. Alternatively, comments can be written using docstrings (strings enclosed with triple quotes).
For example:
#Comments in Python starts with the hash character
print("Comments in a Python code start with a #")
Output:
Comments in a Python code start with a #
In Python, a lambda function is an anonymous function which can have any number of parameters but should contain only one statement.
For example:
a = lambda x,y : x+y print(a(3, 9))
Output:
12
In order to convert a string to lowercase, the function lower() can be used.
For example:
str_name='LEARN'
print(str_name.lower())
Output:
learn
In Python, docstrings are not really comments but are documentation strings. They can be used as comments. It is denoted within triple quotes. Docstrings are not assigned to any variable and therefore serves the purpose of comments as well
For example:
""" Using docstring as a comment. This code divides 2 numbers """ x=12 y=3 z=x/y print(z)
Output:
4.0
In Python, a dictionary is a built-in datatype. It defines a one-to-one relationship between keys and values. Each pair of keys have their corresponding values. They are indexed by keys.
For example,
Consider some key and value pairs such as Name, Age and Blood group (BG).
dict={'Name' : 'James', 'Age' : '25' : 'BG' : 'A+'} print dict[name]
James
print dict[Age]
25
print dict[BG]
A+
Firstly, import OS module and then use os.remove() function in order to delete files in Python.
For example:
import os os.remove("file_name.txt")
The main differences between lambda and def are mentioned below -
Lambda | Def |
---|---|
It is a uni-expression function. | It can hold multiple expressions. |
It forms a function object and returns it. | It generates a function and designates a name to call it. |
It cannot return statements. | It can have a return statement. |
It can be used inside a list and dictionary. | It does not support to get used. |
In Python, sequences are indexed with both positive and negative numbers. The positive numbers use ‘0’ as the first index and ‘1’ as the second index and so on.
Similarly, the index for the negative number starts from ‘-1’ which represents the last index in the sequence and ‘-2’ as the penultimate index and it goes on just like the positive numbers.
The negative index helps in the removal of the new-line spaces from the string and it can also be used to show the index to represent the string in the correct order.
Encapsulation is the process of binding the code and the data together. An example of encapsulation would be a Python class.
Python does not support multiple inheritances as Java does. Multiple inheritances mean that from more than one parent classes a class can be derived.
Polymorphism is the ability to take multiple forms. Suppose if the parent class has a method named XYZ then the child class can have the same name with its own variables and parameters. Python supports polymorphism.
Data Abstraction allows you to provide only the required details and hides the implementation from the world. It can be easily achieved in Python by using interfaces and abstract classes.
Python lays down a convention of prefixing the name of the method/variable with a single or double underscore to emulate the behaviour of protected and private access specifiers. All the members in a Python class are public by default. Also, any member can be accessed from outside the class environment.
In Python, the class keyword is used to create a class.
For example:
class Stduent: def __init__(self, name): self.name = name S1=Student("Steve") print(E=S1.name)
Output:
Steve
An object() returns a featureless object which is a base for all classes. It does not consider any parameters.
In order to reverse a list, use list.reverse() − it reverses objects of the list in place. The reverse() function doesn't return any value. The elements are reversed and the lists are updated.
# Operating System List os = ['Windows', 'macOS', 'Linux'] print('Original List:', os) # List Reverse os.reverse() # updated list print('Updated List:', os)
Output:
Original List: ['Windows', 'macOS', 'Linux'] Updated List: ['Linux', 'macOS', 'Windows']
NumPy is a Python library which is written in C and therefore is one of the fastest and most compatible libraries among the rest. It is a basic library for mathematical or numerical calculation. Some of the basic operations are indexing, reshaping, indexing etc..
On the other hand, SciPy stands for scientific Python and has been written on the top of NumPy. Some of the operations include: Special functions (scipy.special), Integration (scipy.integrate), Optimization (scipy.optimize), Interpolation (scipy.interpolate), Fourier Transforms (scipy.fftpack), Signal Processing (scipy.signal), Linear Algebra (scipy.linalg), Statistics (scipy.stats).
Python supports:
‘+’ : Addition
‘-’ : Subtraction
‘*’ : Multiplication
‘/’ : Division
‘%’ : Modulo division
‘**’ : Power Of
‘//’ : floor div
Python also supports augmented assignment operators such as -
A += 5 means A = A + 5
B -= 7 means B = B - 7
Some other operators Python support are & , |, ~ , ^ which are and, or, bitwise complement and bitwise xor operations.
Python does not support unary operators such as ++ or - operators.
Python allows us to handle loops in an interesting manner by providing a function to write else block for cases when the loop does not satisfy a certain condition.
For example :
x = [ ] for i in x: print "in for loop" else: print "in else block"
Output:
in else block
It works in a similar manner with while-else.
In Python, the tuple() function can be used to convert a list into a tuple. As tuples are immutable, we cannot change it back to a list.
For example:
days = ['sun','mon','tue','wed','thu','fri','sat']
listtoTuple = tuple(days)
print(listtoTuple)
Output:
('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
In Python, set() function can be used to convert a list into a set.
For example:
days = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listtoSet = set(days)
print(listtoSet)
Output:
set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
In the Python list, we can use the count() function to count the occurrences of an individual element.
Example # 1:
days = ['sun','mon','tue','wed','thu','fri','sun','tue','tue', 'tue'] print(days.count('tue'))
Output:
4
Example # 2:
days = ['sun','mon','tue','wed','thu','fri','sun','tue','tue'] print([[x,days.count(x)] for x in set(days)])
Output:
[['wed', 1], ['sun', 2], ['thu', 1], ['tue', 3], ['mon', 1], ['fri', 1]]
Some of the most used text processing methods are mentioned below:
a = 'hello world' a.upper() #Converts to Uppercase 'HELLO WORLD' a.lower() #Converts to Lowercase 'hello world' a.capitalize() #First Letter is capitalized. 'Hello world' a.title() #First character of the every word is capitalized. 'Hello World' a.split() #Splits based on space and returns a list. Split takes an optional parameter to split. By #default it considers space based on which it splits ['hello', 'world'] record = 'name:age:id:salary' #Splitting based on ':' record.split(':') ['name', 'age', 'id', 'salary'] a = '\n\t hello world \t\n' print a hello world a.strip() #strips leading and trailing white spaces and newlines. 'hello world' a.lstrip() #left strip 'hello world \t\n' a.rstrip() #right strip '\n\t\thello world' a = 'hello' a.isalpha() #returns true only if the string contains alphabets. True a = 'hello world' #As there is a space, it returned false. a.isalpha() False a = '1234' >> a.isdigit() #Returns True only if the string contains digits. True a = '1234a' a.isdigit() #returned false as the string contains a alphabet False a.isalnum() # returns true if the string contains alphabets and digits. True a = 'Name: {name}, Age: {age}' a.format(name='Harry', age='22') 'Name: Harry, Age: 22'
In python, we have a method called update() which can be used in order to merge one dictionary on another.
For example:
a = {'a':3} b = {'b':2} a.update(b) a
Output:
{'a': 3, 'b': 2}
In Python, all functions and variables follow lowercase and underscore naming convention. For example,
is_prime(), test_var = 30 etc.
However, constants are either camelcase or uppercase. For example,
Max_val = 20, PI = 3.14
Even for class names, camelcase is followed. For example,
UserNames
In Python, the sys module gives the version of Python being used. The code mentioned below shows how to check for the version.
import sys
print(sys.version)
In order to get the list of all the keys in a dictionary, use function keys(). For example,
mydict={'a':1,'b':2,'c':3,'e':5} mydict.keys() dict_keys(['a', 'b', 'c', 'e'])
def f(x,l=[]): for i in range(x): l.append(i*i) print(l) f(2) f(3,[3,2,1]) f(3)
The output will be:
[0, 1] [3, 2, 1, 0, 1, 4] [0, 1, 0, 1, 4]
Some of the additional data structures are -
The code mentioned below can be used to save an image locally from an URL address.
import urllib.request urllib.request.urlretrieve("URL", "local-filename.jpg")
Random numbers can be generated by using various functions in Python. They are -
In Python, to find the type and identification number of an object, we can use the functions type() and id().
type(<variableName>) - It gives us the type of the object that variable is pointing to.
id(<variablename>) - It gives us the unique identification number of the object that variable is pointing to.
In Python, an iterator is an object which can be iterated upon. It is an object which will return data, only one element at a time. Python iterator should implement two special methods, __iter__() and __next__(), which are collectively known as iterator protocol.
Most of the built-in containers in Python such as list, tuples, string etc. are iterables and an object is called iterable only if we can get an iterator from it. The iter() function returns an iterator from them.
mytuple = ("alice", "bob", "charlie") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))o
alice bob charlie
In Python, a generator is a type of function which allows us to specify a function which acts as an iterator and therefore can be used in a ‘for’ loop. In a generator function, the yield keyword replaces the return statement.
# Simple Python function def fn(): return "Simple Python function." # Python Generator function def generate(): yield "It is a PG function." print(next(generate()))
The output is:
It is a PG function.
In Python, decorator allows us to add new behaviour to the given objects dynamically. In the example below, a simple program shows how to display a message pre and post the execution of a function.
def deco_sample(func): def deco_hook(*args, **kwargs): print("Before the function is called") result = func(*args, **kwargs) print("After the function is called") return result return deco_hook @deco_sample def product(x, y): "Function to multiply two numbers." return x * y print(product(6, 6))
The output is:
Before the function is called
After the function is called
36
In Python, we can use two approaches in order to copy an object, Shallow Copy and Deep Copy.
Shallow Copy- In this approach, a new object is created which stores the reference of the original elements. A shallow copy simply copies the reference of nested objects and do not create a copy of nested objects.
For example,
import copy list_old = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] list_new = copy.copy(list_old) print("Old list:", list_old) print("New list:", list_new)
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Deep Copy- In this approach, a new object is created and it recursively adds the copies of nested objects which are present in the original elements. In the example below, we will create a deep copy using deepcopy() function which is present in the copy module.
For example,
import copy list_old = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] list_new = copy.deepcopy(old_list) print("Old list:", list_old) print("New list:", list_new)
Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]] New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
The main() function is said to be the entry point of a program, which is called first in most of the programming languages. In Python, the interpreter first executes the source file code in a sequential manner and do not call any method if it isn’t part of the code. However, if it is directly a part of the code then it is executed while the file is imported as a module.
To define this main method, there is a special technique used so that it is executed only when the program is run directly and not when it is imported as a module. A simple example mentioned below shows how to define python main function.
print("Hello") print("__name__ value: ", __name__) def main(): print("Print the main function") if __name__ == '__main__': main()
The output:
Hello __name__ value: __main__ Print the main function
In Python, the rstrip() function can be used to duplicate the string but it leaves out the whitespace characters from the end. This function excludes the characters from the right end as per the argument value i.e, a string mentioning the group of characters to get excluded.
The signature of the rstrip() is:
str.rstrip([char sequence/pre>
For example,
str_name = 'Python'
#The white spaces are excluded
print(str_name.rstrip())
To handle Exceptions, Python provides constructs such as Try, Except, Finally. The unsafe code is indented under the Try block and then the fall-back code is kept inside the Except block. Lastly, any kind of instructions intended for execution comes under the Finally block.
try: print("Executing code in the try block") print(exception) except: print("Entering in the except block") finally: print("Reached the final block")
The output is:
Executing code in the try block Entering in the except block Reached the final block
In Python, globals() function returns the current global symbol table as a dictionary object. To keep all necessary information about a program, python maintains a symbol table. The information in this table remains in the global scope of the program and we can retrieve it by using the globals() method.
For example:
x = 8 def fn(): y = 7 z = y + x # Calling the globals() method z = globals()['x'] = z return z # Test Code ret = fn() print(ret)
The output is:
15
In Python, closures are function objects which are returned by another function. It is used to eliminate code redundancy.
In the example below, it shows a simple closure for multiplying numbers
def multiply_number(num): def product(number): 'product() here is a closure' return num * number return product num_2 = multiply_number(3) print(num_2(11)) print(num_2(30)) num_6 = multiply_number(6) print(num_6(1))
The output is:
33
90
6
The pass statement is the statement which is a null operation. No operations take place when the pass statement is executed. It results in no operation (NOP). Python statements are case sensitive, so you should always write “pass” in lowercase, if you write “Pass”, an error will be shown: “NameError: name Pass is not defined.”
For example,
# pass is just a placeholder for # functionality to be added later. sequence = {'p', 'a', 's', 's'} for val in sequence: pass
The optional statements that can be used in the try-except block are-
It is used if you would like to run a piece of code when the try block does not create an exception.
It is used when you would like to execute some steps which run irrespective of whether an exception occurs or not.
*args is used as a parameter in the function header. It allows us to pass N (variable) number of arguments. However, it does not allow passing a named argument to the function.
For example, let us see a python code to demonstrate *args for dynamic arguments.
def fn(*argList): for argx in argList: print (argx) fn('Let', 'Us', 'Learn', 'Python')
The output:
Let Us Learn Python
The split() function can be used to separate large strings into smaller ones or rather sub-strings. We can either use a separator for the split else it will use the space as one by default.
For example,
str_name = 'alice bob charlie' str_name.split(" ") str_name.split()
The output will be -
['alice', 'bob', 'charlie'] ['alice', 'bob', 'charlie']
title() method can be used to convert the first letter in each word to capital (uppercase) and the rest turns to lowercase.
For example,
str_name = 'cOnTInuOus lEarnIng'
str_name.title()
The output will be -
Continuous Learning
Iterable is a type of object which would generate an Iterator when passed to in-built method iter()
For an object to be iterable, the class of the object needs to define two instance methods: __len__ and __getitem__. Such an object, when passed to method iter(), would generate an iterator.
Iterator is the object which is used to iterate over an iterable object. It provides __next__ method to do so. The __next__ method is implicitly called when we use it in for loop.
In Python, lists and arrays store data in a similar manner. However, arrays hold only single data type elements whereas lists can hold any data type elements.
For example:
import array as arr My_Array=arr.array('i',[1,2,3,4]) My_list=[1,'abc',1.20] print(My_Array) print(My_list)
Output:
array('i', [1, 2, 3, 4]) [1, 'abc', 1.2]
In order to reverse the order of an array we can use [::-1]
For example:
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])
Operators are considered to be special functions. They accept one or more than one values and produce a corresponding result.
is: It returns true when 2 operands are true (Example: “a” is ‘a’)
not: It returns the inverse of the boolean value.
in: It checks if some element is present in some sequence
Both the functions, help() and dir() can be accessed from the Python interpreter and is used to view a consolidated dump of built-in functions.
help() function - It is used to display the documentation string and it also facilitates you to check the help related to keywords, modules or attributes etc..
dir() function - It is used to display the defined symbols.
In order to add values or elements you can use functions like append(), extend() and the insert (i,x).
For example:
a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.append(3.4) print(a) a.extend([4.5,6.3,6.8]) print(a) a.insert(2,3.8) print(a)
Output:
array('d', [1.1, 2.1, 3.1, 3.4]) array('d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8]) array('d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])
In order to remove values or elements, we can use pop() and remove() methods. The main difference between these two functions is that pop() function returns the deleted value and remove() function do not.
For example:
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6]) print(a.pop()) print(a.pop(3)) a.remove(1.1) print(a)
Output:
4.6 3.1 array('d', [2.2, 3.8, 3.7, 1.2])
We can calculate percentiles with the following code
import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p)
Output:
3
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) A1 = range(10)A2 = sorted([i for i in A1 if i in A0]) A3 = sorted([A0[s] for s in A0]) A4 = [i for i in A1 if i in A3] A5 = {i:i*i for i in A1} A6 = [[i,i*i] for i in A1] print(A0,A1,A2,A3,A4,A5,A6)
The following will be the final outputs of A0, A1, … A6
A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary A1 = range(0, 10) A2 = [] A3 = [1, 2, 3, 4, 5] A4 = [1, 2, 3, 4, 5] A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
To get the indices of N maximum values in a NumPy array you can use the below code:
import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1])
Output:
[ 4 3 1 ]
In order to sort a list in Python, the following code can be used :
list = ["1", "4", "0", "6", "9"] list = [int(i) for i in list] list.sort() print (list)
a=input("enter a sequence") b=a[::-1] if a==b: print("palindrome") else: print("Not a Palindrome")
Output:
enter a sequence 656 palindrome
a=int(input("enter a number")) if a>1: for x in range(2,a): if(a%x)==0: print("not prime") break else: print("Prime") else: print("not prime") for x in range(2,a): if(a%x)==0: print("not prime")
Output:
enter a number 3 Prime
# Enter number of terms needed #0,1,1,2,3,5.... a=int(input("Enter the terms")) f=0 #first element of series s=1 #second element of series if a<=0: print("The requested series is\n",f) else: print(f,s,end=" ") for x in range(2,a): next=f+s print(next,end=" ") f=s s=next
Output:
Enter the terms 5 0 1 1 2 3
def bs(a): # a = name of list b=len(a)-1 # minus 1 because we always compare 2 adjacent values #number of rounds will be 1 less than the total length of the list for x in range(b): for y in range(b-x): if a[y]>a[y+1]: a[y],a[y+1]=a[y+1],a[y] return a a=[46,3,5,4,2,68,92] bs(a)
Output:
[2, 3, 4, 5, 46, 68, 92]
def list_sum(list_num): if len(list_num) == 1: return list_num[0] else: return list_num[0] + list_sum(list_num[1:]) print(list_sum([3, 8, 2, 4, 5]))
Output:
22
A class which do not have any code defines within its block is known as an empty class. An empty class can be created using a pass keyword. However, objects can be created outside the class itself.
For example-
class x: pass obj=x() obj.name="abc" print("Name = ",obj.name)
Output:
Name = abc
In Python, memory management involves a private heap of Python objects and data structures. The interpreter takes control of Python heap and the developer does not have access to it.
Allocation of heap space for Python objects is assigned by the Python memory manager. There are certain tools provided by the core API of Python which helps to code reliable and more robust program.
Python has a built-in garbage collector, all the unused memory is recycled here. The GC module can be enabled and disabled by using defined functions-
gc.enable () - It enables the garbage collector for automatic garbage collection
gc.disable() - It disables the garbage collector for automatic garbage collection.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = (i for i in a if i%3 == 0) #Generator expression. for i in b: print i, 0 3 6 9
The term monkey patch refers to dynamically modifying a class or module at run-time. In Python, we change the behaviour of code at run-time. Let us look into an example to understand in a better way.
# monk.py class A: def func(self): print "Calling func()"
In the above code, we created a module and will be using later in order to change the behaviour of func() at run-time by assigning various values.
import monk def monkey_f(self): print "monkey_f() is being called" # replacing the address of "func" with "monkey_f" monk.A.func = monkey_f obj = monk.A() # calling function "func" whose address got replaced # with function "monkey_f()" obj.func()
Output:
monkey_f() is being called
A class is also called the child/derived/subclass inheriting from the parent/base/superclass when it inherits. It inherits all attributes and methods from another class.
Inheritance allows us to reuse our code and make it simpler to create and maintain applications. Python supports -
A higher order function returns a new function by accepting one or more functions as input. In order to make high order functions, we will have to first import functools module. Functions like functools.partial() is often used for high order function. The functions act on or else return the other functions. For this particular module, the callable object can be treated as a function.
Python libraries are a collection of Python packages. Some of the majorly used python libraries are –Numpy, Pandas, Matplotlib, Scikit-learn and many more.
In Python, we can use other numbering systems apart from decimal such as binary, octal, and hexadecimal.
In Python, the enumerate() function is used to add a counter to an iterable object. enumerate() function accepts sequential indexes starting from zero.
For example,
subjects = ('Python', 'Java', 'C++') for i, subject in enumerate(subjects): print(i, subject)
Output:
0 Python 1 Java 2 C++
It’s the time to acquaint you with the questions which you might face during your interview and will help you to crack Python interview easily & pursue your dream career.
Python has turned out to be the most in-demand programming language in recent years. Many IT companies that hunt for good Python programmers are ready to pay the best salaries to the eligible candidates. Hence, we have covered the top commonly asked Python interview questions to familiarize you with the knowledge and skills required to succeed in your next Python job interview.
Going through these Python programming interview questions will help you to land your dream job in Data Science, Machine Learning or just Python coding. These Python basic interview questions will surely boost your confidence to face an interview and will definitely prepare you to answer the toughest of questions in the best way possible. These Python developer interview questions are suggested by experts and have proven to have great value.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.