Python Interview Questions

What is Python?

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it h
as fewer syntactical constructions than other languages.

What are the supported data types in Python?

Python has five standard data types:

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

What is tuples in Python?

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

What is the difference between tuples and lists in Python?

The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

What are Python's dictionaries?

Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Name some of the features of Python?

Following are some of the salient features of python −

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

How will you create a dictionary in python?

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict[‘one’] = “This is one”
dict[2]     = “This is two”
tinydict = {‘name’: ‘john’,’code’:6734, ‘dept’: ‘sales’}

What is Python really? You can (and are encouraged) make comparisons to other technologies in your answer

Here are a few key points:

  • Python is an interpreted language. That means that, unlike languages like Cand its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
  • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111and then x=”I’m a string”without error
  • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private), the justification for this point is given as “we are all adults here”
  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately, Python allows the inclusion of C based extensions so bottlenecks can be optimised away and often are. The numpypackage is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python
  • Python finds use in many spheres – web applications, automation, scientific modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.
  • Python makes difficult things easy so programmers can focus on overriding algorithms and structures rather than nitty-gritty low level details.

Why is it called Python?

When he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty Python’s Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.

What is the interpreter in Python?

An interpreter is a program that reads and executes code. This includes source code, pre-compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters, which execute Perl, Python, and Ruby code respectively.

What does a python do?

Python is a general-purpose programming language typically used for web development. … SQLite is one free lightweight database commonly used by Pythonprogrammers to store data. Many highly trafficked websites, such as YouTube, are created using Python.

Describe Python's garbage collection mechanism in brief.

A lot can be said here. There are a few main points that you should mention:

  • Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else
  • occasionally things called “reference cycles” happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1and o2 such that x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn’t be live. But each of them has a reference count of 1.
  • Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first.

This explanation is CPython specific.

What is the output of print str if str = 'Hello World!'?

It will print complete string. Output would be Hello World!.

What is the output of print str`{`0`}` if str = 'Hello World!'?

It will print first character of the string. Output would be H.

What is the output of print str`{`2:5`}` if str = 'Hello World!'?

It will print characters starting from 3rd to 5th. Output would be llo.

What is the output of print str`{`2:`}` if str = 'Hello World!'?

It will print characters starting from 3rd character. Output would be llo World!.

What is the output of print str * 2 if str = 'Hello World!'?

It will print string two times. Output would be Hello World!Hello World!.

What is the output of print str + ``TEST`` if str = 'Hello World!'?

It will print concatenated string. Output would be Hello World!TEST.

What is the output of print list if list = `{` 'abcd', 786 , 2.23, 'john', 70.2 `}`?

It will print concatenated lists. Output would be [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ].

What is the output of print list`{`0`}` if list = `{` 'abcd', 786 , 2.23, 'john', 70.2 `}`?

It will print first element of the list. Output would be abcd.

What is the output of print tuple`{`1:3`}` if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).

What is the output of print tuple`{`2:`}` if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print elements starting from 3rd element. Output would be (2.23, ‘john’, 70.200000000000003).

What is the output of print tinytuple * 2 if tinytuple = (123, ‘john’)?

It will print tuple two times. Output would be (123, ‘john’, 123, ‘john’).

What is the output of print tuple + tinytuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2) and tinytuple = (123, ‘john’)?

It will print concatenated tuples. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’).

What are Python’s dictionaries?

Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

How will you create a dictionary in python?

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict[‘one’] = “This is one”
dict[2]     = “This is two”
tinydict = {‘name’: ‘john’,’code’:6734, ‘dept’: ‘sales’}

How will you get all the keys from the dictionary?

Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys()   # Prints all the keys

How will you get all the values from the dictionary?

Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values()   # Prints all the values

How will you convert a string to an int in python?

int(x [,base]) – Converts x to an integer. base specifies the base if x is a string.

How will you convert a string to a long in python?

long(x [,base] ) – Converts x to a long integer. base specifies the base if x is a string.

How will you convert a string to a float in python?

float(x) − Converts x to a floating-point number.

How will you convert a object to a string in python?

str(x) − Converts object x to a string representation.

How will you convert a object to a regular expression in python?

repr(x) − Converts object x to an expression string.

How will you convert a String to an object in python?

eval(str) − Evaluates a string and returns an object.

How will you convert a string to a tuple in python?

tuple(s) − Converts s to a tuple.

How will you convert a string to a list in python?

list(s) − Converts s to a list.

How will you convert a string to a set in python?

set(s) − Converts s to a set.

How will you create a dictionary using tuples in python?

dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.

How will you convert a string to a frozen set in python?

frozenset(s) − Converts s to a frozen set.

How will you convert an integer to a character in python?

chr(x) − Converts an integer to a character.

How will you convert an integer to an unicode character in python?

unichr(x) − Converts an integer to a Unicode character.

How will you convert a single character to its integer value in python?

ord(x) − Converts a single character to its integer value.

How will you convert an integer to hexadecimal string in python?

hex(x) − Converts an integer to a hexadecimal string.

How will you convert an integer to octal string in python?

oct(x) − Converts an integer to an octal string.

What is the purpose of ** operator?

** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.

What is the purpose of // operator?

// Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.

What is the purpose of is operator?

is − Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).

What is the purpose of not in operator?

not in − Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

What is the purpose break statement in python?

break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop.

What is the purpose continue statement in python?

Continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

What is the purpose pass statement in python?

pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

How can you pick a random item from a list or tuple?

choice(seq) − Returns a random item from a list, tuple, or string.

How can you pick a random item from a range?

randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step).

How can you get a random number in python?

random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.

How will you set the starting value in generating random numbers?

seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

How will you randomizes the items of a list in place?

shuffle(lst) − Randomizes the items of a list in place. Returns None.

How will you capitalizes first letter of string?

capitalize() − Capitalizes first letter of string.

How will you check in a string that all characters are alphanumeric?

isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

How will you check in a string that all characters are digits?

isdigit() − Returns true if string contains only digits and false otherwise.

How will you check in a string that all characters are in lowercase?

islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

How will you check in a string that all characters are numerics?

isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.

How will you check in a string that all characters are whitespaces?

isspace() − Returns true if string contains only whitespace characters and false otherwise.

How will you check in a string that it is properly titlecased?

istitle() − Returns true if string is properly “titlecased” and false otherwise.

How will you check in a string that all characters are in uppercase?

isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

How will you merge elements in a sequence?

join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

How will you get the length of the string?

len(string) − Returns the length of the string.

How will you get a space-padded string with the original string left-justified to a total of width columns?

just(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width columns.

How will you convert a string to all lowercase?

lower() − Converts all uppercase letters in string to lowercase.

How will you remove all leading whitespace in string?

strip() − Removes all leading whitespace in string.

How will you get the max alphabetical character from the string?

max(str) − Returns the max alphabetical character from the string str.

How will you get the min alphabetical character from the string?

min(str) − Returns the min alphabetical character from the string str.

How will you replaces all occurrences of old substring in string with new string?

replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.

How will you remove all leading and trailing whitespace in string?

strip([chars]) − Performs both lstrip() and rstrip() on string.

How will you change case for all letters in string?

swapcase() − Inverts case for all letters in string.

How will you get titlecased version of string?

title() − Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.

How will you convert a string to all uppercase?

upper() − Converts all lowercase letters in string to uppercase.

How will you check in a string that all characters are decimal?

isdecimal() − Returns true if a unicode string contains only decimal characters and false otherwise.

What is the difference between del() and remove() methods of list?

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know.

What is the output of len(`{`1, 2, 3`}`)?

3.

What is the output of `{`1, 2, 3`}` + `{`4, 5, 6`}`?

[1, 2, 3, 4, 5, 6]

What is the output of `{`‘Hi!’`}` * 4?

[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]

What is the output of 3 in `{`1, 2, 3`}`?

True

What is the output of for x in `{`1, 2, 3`}`: print x?

1 2 3

What is the output of L`{`2`}` if L = `{`1,2,3`}`?

3, Offsets start at zero.

What is the output of L`{`-2`}` if L = `{`1,2,3`}`?

L[-1] = 3, L[-2]=2, L[-3]=1

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 will you get the index of an object in a list?

list.index(obj) − Returns the lowest index in list that obj appears.

How will you insert an object at given index in a list?

list.insert(index, obj) − Inserts object obj into list at offset index.

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.

How will you sort a list?

list.sort([func]) − Sorts objects of list, use compare func if given.

Name five modules that are included in python by default (many people come searching for this, so I included some more examples of modules which are often used)?

datetime           (used to manipulate date and time)
re                         (regular expressions)
urllib, urllib2  (handles many HTTP things)
string                  (a collection of different groups of strings for example all lower_case letters etc)
itertools            (permutations, combinations and other useful iterables)
ctypes                (from python docs: create and manipulate C data types in Python)
email                  (from python docs: A package for parsing, handling, and generating email messages)
__future__      (Record of incompatible language changes. like division operator is different and much better when imported from __future__)
sqlite3               (handles database of SQLite type)
unittest             (from python docs: Python unit testing framework, based on Erich Gamma’s JUnit and Kent Beck’s Smalltalk testing framework)
xml                     (xml support)
logging              (defines logger classes. enables python to log details on severity level basis)
os                        (operating system support)
pickle                (similar to json. can put any data structure to external files)
subprocess    (from docs: This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes)
webbrowser  (from docs: Interfaces for launching and remotely controlling Web browsers.)
traceback       (Extract, format and print Python stack traces)

Name a module that is not included in python by default?

mechanize
django
gtk
A lot of other can be found at pypi.

What is __init__.py used for?

It declares that the given directory is a  package. #Python Docs (From Endophage‘s comment)

When is pass used for?

pass does nothing. It is used for completing the code where we need something. For eg:

12 class abc():pass

What is a docstring?

docstring is the documentation string for a function. It can be accessed by

function_name.__doc__

it is declared as:

12 def function_name():“””your docstring”””

Writing documentation for your progams is a good habit and makes the code more understandable and reusable.

What is list comprehension?

Creating a list by doing some operation over data that can be accessed using an iterator. For eg:

12

3

>>>[ord(i) for i in string.ascii_uppercase][65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]

>>>

What is map?

map executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given.  #Follow the link to know more similar functions
For eg:

12

3

4

5

>>>a=’ayush’>>>map(ord,a)

….  [97, 121, 117, 115, 104]

>>> print map(lambda x, y: x*y**2, [1, 2, 3], [2, 4, 1])

….  [4, 32, 3]

12

3

4

5

6

7

8

9

10

11

Help on built-in function map in module __builtin__:

map(…)

map(function, sequence[, sequence, …]) -> list

 

Return a list of the results of applying the function to the items of

the argument sequence(s).  If more than one sequence is given, the

function is called with an argument list consisting of the corresponding

item of each sequence, substituting None for missing values when not all

sequences have the same length.  If the function is None, return a list of

the items of the sequence (or a list of tuples if more than one sequence).

#Python Docs

Summary
Review Date
Reviewed Item
Very Nice! Very Helpful Python Interview Questions and and Answers, Good work Iteanz, Keep Updating More.
Author Rating
51star1star1star1star1star