Skip to main content

Top 15 Python Questions and Answers

Q-1. What Is The Function To Randomize The Items Of A List In-Place?

Ans. Python has a built-in module called as <random>. It exports a public method <shuffle(<list>)> which can randomize any input sequence.
import random
list = [2, 18, 8, 4]
print "Prior Shuffling - 0", list
random.shuffle(list)
print "After Shuffling - 1", list
random.shuffle(list)
print "After Shuffling - 2", list

Q-2. What Is The Best Way To Split A String In Python?

Ans. We can use Python <split()> function to break a string into substrings based on the defined separator. It returns the list of all words present in the input string.
test = "I am learning Python."
print test.split(" ")

Program Output.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

['I', 'am', 'learning', 'Python.']

Q-3. What Is The Right Way To Transform A Python String Into A List?

Ans. In Python, strings are just like lists. And it is easy to convert a string into the list. Simply by passing the string as an argument to the list would result in a string-to-list conversion.
list("I am learning Python.")

Program Output.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

=> ['I', ' ', 'a', 'm', ' ', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', ' ', 'P', 'y', 't', 'h', 'o', 'n', '.']

Q-4. How Does Exception Handling In Python Differ From Java? Also, List The Optional Clauses For A <Try-Except> Block In Python?

Ans. Unlike Java, Python implements exception handling in a bit different way. It provides an option of using a <try-except> block where the programmer can see the error details without terminating the program. Sometimes, along with the problem, this <try-except> statement offers a solution to deal with the error.
There are following clauses available in Python language.
1. try-except-finally
2. try-except-else

Q-5. What Do You Know About The <List> And <Dict> Comprehensions? Explain With An Example.

Ans. The <List/Dict> comprehensions provide an easier way to create the corresponding object using the existing iterable. As per official Python documents, the list comprehensions are usually faster than the standard loops. But it’s something that may change between releases.

The <List/Dict> Comprehensions Examples.

#Simple Iteration
item = []
for n in range(10):
    item.append(n*2)
print item

#List Comprehension
item = [n*2 for n in range(10)]
print item

Both the above example would yield the same output.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

#Dict Comprehension
item = {n: n*2 for n in range(10)}
print item

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

💡 Fact – In interactive mode, the last printed expression is assigned to the variable _ (underscore).

Q-6. What Are The Methods You Know To Copy An Object In Python?

Ans. Commonly, we use <copy.copy()> or <copy.deepcopy()> to perform copy operation on objects. Though not all objects support these methods but most do.
But some objects are easier to copy. Like the dictionary objects provide a <copy()> method.

Example.

item = {n: n*2 for n in range(10)}
newdict = item.copy()
print newdict

Q-7. Can You Write Code To Determine The Name Of An Object In Python?

Ans. No objects in Python have any associated names. So there is no way of getting the one for an object. The assignment is only the means of binding a name to the value. The name then can only refer to access the value. The most we can do is to find the reference name of the object.

Example.

class Test:
    def __init__(self, name):
        self.cards = []
        self.name = name

    def __str__(self):
        return '{} holds ...'.format(self.name)
        
obj1 = Test('obj1')
print obj1

obj2 = Test('obj2')
print obj2

Q-8. Can You Write Code To Check Whether The Given Object Belongs To A Class Or Its Subclass?

Ans. Python has a built-in method to list the instances of an object that may consist of many classes. It returns in the form of a table containing tuples instead of the individual classes. Its syntax is as follows.
<isinstance(obj, (class1, class2, ...))>
The above method checks the presence of an object in one of the classes. The built-in types can also have many formats of the same function like <isinstance(obj, str)> or <isinstance(obj, (int, long, float, complex))>.
Also, it’s not recommended to use the built-in classes. Create an user-defined class instead.
We can take the following example to determine the object of a particular class.

Example.

def lookUp(obj):
    if isinstance(obj, Mailbox):
        print "Look for a mailbox"
    elif isinstance(obj, Document):
        print "Look for a document"
    else:
        print "Unidentified object"

Q-9. What Is The Result Of The Following Python Program?

Ans. The example code is as follows.
def multiplexers ():

    return [lambda n: index * n for index in range (4)]

print [m (2) for m in multiplexers ()]

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

[6, 6, 6, 6]

The output of the above code is <[6, 6, 6, 6]>. It’s because of the late binding as the value of the variable <index> gets looked up after a call to any of multiplexers functions.

Q-10. What Is The Result Of The Below Lines Of Code?

Here is the example code.
def fast (items= []):
    items.append (1)
    return items

print fast ()
print fast ()
Ans. The above code will give the following result.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

[1]
[1, 1]
The function <fast> evaluates its arguments only once after the function gets defined. However, since <items> is a list, so it’ll get modified by appending a <1> to it.
💡 Fact – You can inspect objects in Python by using dir().

Q-11. What Is The Result Of The Below Python Code?

keyword = 'aeioubcdfg'
print keyword [:3] + keyword [3:]
Ans. The above code will produce the following result.
<'aeioubcdfg'>
In Python, while performing string slicing, whenever the indices of both the slices collide, a <+> operator get applied to concatenates them.

Q-12. How Would You Produce A List With Unique Elements From A List With Duplicate Elements?

Ans. Iterating the list is not a desirable solution. The right answer should look like this.
duplicates = ['a','b','c','d','d','d','e','a','b','f','g','g','h']
uniqueItems = list(set(duplicates))
print sorted(uniqueItems)

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Q-13. Can You Iterate Over A List Of Words And Use A Dictionary To Keep Track Of The Frequency(Count) Of Each Word? Consider The Below Example.

{'Number':Frequency, '2':2, '3':2}
Ans. Please find out the below code.
def dic(words):
  wordList = {}
  for index in words:
    try:
      wordList[index] += 1
    except KeyError:
      wordList[index] = 1
  return wordList
 
wordList='1,3,2,4,5,3,2,1,4,3,2'.split(',')
print wordList

print dic(wordList)

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2']
{'1': 2, '3': 3, '2': 3, '5': 1, '4': 2}

Q-14. What Is The Result Of The Following Python Code?

class Test(object):
    def __init__(self):
        self.x = 1
 
t = Test()
print t.x
print t.x
print t.x
print t.x
Ans. All print statement will display <1>. It’s because the value of object’s attribute(x) is never changing.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

1
1
1
1
Also, <x> becomes a part of the public members of class Test.
Hence, it can be accessed directly.

Q-15. Can You Describe What’s Wrong With The Below Code?

testProc([1, 2, 3]) # Explicitly passing in a list
testProc()  # Using a default empty list
 
def testProc(n = []):
    # Do something with n
 
print n
Ans. The above code would throw a <NameError>.
The variable n is local to the function <testProc> and can’t be accessed outside.
So, printing it won’t be possible.

Popular posts from this blog

How to read or extract text data from passport using python utility.

Hi ,  Lets get start with some utility which can be really helpful in extracting the text data from passport documents which can be images, pdf.  So instead of jumping to code directly lets understand the MRZ, & how it works basically. MRZ Parser :                 A machine-readable passport (MRP) is a machine-readable travel document (MRTD) with the data on the identity page encoded in optical character recognition format Most travel passports worldwide are MRPs.  It can have 2 lines or 3 lines of machine-readable data. This method allows to process MRZ written in accordance with ICAO Document 9303 (endorsed by the International Organization for Standardization and the International Electrotechnical Commission as ISO/IEC 7501-1)). Some applications will need to be able to scan such data of someway, so one of the easiest methods is to recognize it from an image file. I 'll show you how to retrieve the MRZ information from a picture of a passport using the PassportE

How to generate class diagrams pictures in a Django/Open-edX project from console

A class diagram in the Unified Modeling Language ( UML ) is a type of static structure diagram that describes the structure of a system by showing the system’s classes, their attributes, operations (or methods), and the relationships among objects. https://github.com/django-extensions/django-extensions Step 1:   Install django extensions Command:  pip install django-extensions Step 2:  Add to installed apps INSTALLED_APPS = ( ... 'django_extensions' , ... ) Step 3:  Install diagrams generators You have to choose between two diagram generators: Graphviz or Dotplus before using the command or you will get: python manage.py graph_models -a -o myapp_models.png Note:  I prefer to use   pydotplus   as it easier to install than Graphviz and its dependencies so we use   pip install pydotplus . Command:  pip install pydotplus Step 4:  Generate diagrams Now we have everything installed and ready to generate diagrams using the comm

How to Remove course from Open-edX

Go to vagrant  => 1. In the edx-platform directory:  - cd /edx/app/edxapp/edx-platform 2. Run the following Django management command:   - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp lms dump_course_ids --settings aws    - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp lms dump_course_ids --settings=devstack 3. Find the course ID which you'd like to delete in the resulting list of course IDs. 4. Copy the course ID into the following command and run it:  - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp cms delete_course <COURSE_ID> --settings aws  -   sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp cms delete_course <COURSE_ID> --settings=devstack  - You'll be asked to verify the deletion . To verify the deletion, run the command from step 2 above and ensure that the course ID is not in the list. Help reference : https://openedx.atlassian.net/wiki/spa