VeriSign Most Frequently Asked Latest Python Interview Questions Answers

What Are The Optional Statements That Can Be Used Inside A <Try-Except> Block In Python?

There are two optional clauses you can use in the <try-except> block.

The <else> clause
It is useful if you want to run a piece of code when the try block doesn’t create any exception.
The <finally> clause
It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.

What is the output of L[1:] if L = [1,2,3]?

2, 3, Slicing fetches sections.

How will you compare two lists?

cmp(list1, list2) − Compares elements of both lists.

How will you get the length of a list?

len(list) − Gives the total length of the list.

How will you get the max valued item of a list?

max(list) − Returns item from the list with max value.

How will you get the min valued item of a list?

min(list) − Returns item from the list with min value.

How Does The Ternary Operator Work In Python?

The ternary operator is an alternative for the conditional statements. It combines of the true or false values with a statement that you need to test. The syntax would look like the one given below.

[onTrue] if [Condition] else [onFalse]

x, y = 35, 75
smaller = x if x < y else y
print(smaller)
VeriSign Most Frequently Asked Latest Python Interview Questions Answers
VeriSign Most Frequently Asked Latest Python Interview Questions Answers

What Does The <Self> Keyword Do?

The <self> keyword is a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as hidden parameter.

 What Are Different Methods To Copy An Object In Python?

There are two ways to copy objects in Python.

copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.

What Is The Purpose Of Doc Strings In Python?

In Python, documentation string is popularly known as doc strings. It sets a process of recording Python functions, modules, and classes.

Which Python Function Will You Use To Convert A Number To A String?

For converting a number into a string, you can use the built-in function <str()>.  If you want an octal or hexadecimal representation, use the inbuilt function <oct()> or <hex()>.

 How Do You Debug A Program In Python? Is It Possible To Step Through Python Code?

Yes, we can use the Python debugger (<pdb>) to debug any Python program. And if we start a program using <pdb>, then it let us even step through the code.

 List Down Some Of The PDB Commands For Debugging Python Programs?

Here are a few PDB commands to start debugging Python code.

Add breakpoint – <b>
Resume execution – <c>
Step by step debugging – <s>
Move to next line – <n>
List source code – <l>
Print an expression – <p>

What Is The Command To Debug A Python Program?

The following command helps run a Python program in debug mode.

$ python -m pdb python-script.py

Why And When Do You Use Generators In Python?

A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.

Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

We can replace loops with generators for efficiently calculating results involving large data sets.
Generators are useful when we don’t want all the results and wish to hold back for some time.
Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.

How will you remove last object from a list?

list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

How will you remove an object from a list?

list.remove(obj) − Removes object obj from list.

How will you reverse a list?

list.reverse() − Reverses objects of list in place.

What Does The <Yield> Keyword Do In Python?

The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.

See the example below.

def testgen(index):
  weekdays = ['sun','mon','tue','wed','thu','fri','sat']
  yield weekdays[index]
  yield weekdays[index+1]

day = testgen(0)
print next(day), next(day)

output: sun mon

How To Convert A List Into Other Data Types?

Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.

Turn A List Into A String.

We can use the <”.join()> method which combines all elements into one and returns as a string.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)

output: sun mon tue wed thu fri sat

Turn A List Into A Tuple.

Call Python’s <tuple()> function for converting a list into a tuple. This function takes the list as its argument. But remember, we can’t change the list after turning it into a tuple because it becomes immutable.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)

output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
Turn A List Into A Set.
Converting a list to a set poses two side-effects.

Set doesn’t allow duplicate entries, so the conversion will remove any such item if found.
A set is an ordered collection, so the order of list items would also change.
However, we can use the <set()> function to convert a list to a set.

weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)

output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])

Turn A List Into A Dictionary.

In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.

However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.

Passing the tuples into the <dict()> function would finally turn them into a dictionary.

weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)

output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}

How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?

Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.

Count The Occurrences Of An Individual Item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))

output: 3

What Is NumPy And How Is It Better Than A List In Python?

NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.

Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.

NumPy arrays are more compact than lists.
Reading and writing items is faster with NumPy.
Using NumPy is more convenient than to the standard list.
NumPy arrays are more efficient as they augment the functionality of lists in Python.

What Are Different Ways To Create An Empty NumPy Array In Python?

There are two methods which we can apply to create empty NumPy arrays.

The First Method To Create An Empty Array.

import numpy
numpy.array([])

The Second Method To Create An Empty Array.

# Make an empty NumPy array
numpy.empty(shape=(0,0)).

What are the ways to write a function using call by reference?

Arguments in python are passed as an assignment. This assignment creates an object that has no relationship between an argument name in source and target. The procedure to write the function using call by reference includes:

The tuple result can be returned to the object which called it. The example below shows it:

def function(a, b):
a = 'value'
b = b + 1
# a and b are local variables that are used to assign the new objects
return a, b

# This is the function that is used to return the value stored in b
- The use of global variables allows the function to be called as reference but this is not the safe method to call any function.
- The use of mutable (they are the classes that consists of changeable objects) objects are used to pass the function by reference.
def function(a):
a[0] = 'string'
a[1] = a[1] + 1

# The ‘a’ array give reference to the mutable list and it changes the changes that are shared
args = ['string', 10]
func1(args)
print args[0], args[1]

#This prints the value stored in the array of ‘a’.

Post a Comment

Previous Post Next Post