Python Interview Questions (Part 3)

When does dictionary is used instead of a list?

You would only use the Dictionary if you needed to map (or associate) meaningful keys to values, whereas a List only maps (or associates) positions (or indices) to values.

How to sort a dictionary by key?

import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) print(sorted_x)
output
[(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]

How to sort a dictionary by value?

import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) print(sorted_x)
output
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]

What do you mean by list comprehension?

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

lst = [x**2 for x in range(10)] print(lst)
output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

same as :

lst = [] for x in range(10): lst.append(x**2) print(lst)
output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

How to clone or copy a list?

Python 3.3+ adds list.copy() method, which should be as fast as slicing:
newlist = old_list.copy()

How to remove duplicates from a list ?

itemList = ['1', '2', '3', '3', '6', '4', '5', '6'] newList = [] [newList.append(item) for item in itemList if item not in newList] print(newList)
output
['1', '2', '3', '6', '4', '5']

What is a built-in function that Python uses to iterate over a number sequence?

The range() is the built-in function to be used for iterating the sequence of numbers.
for num in range (1, 5): print (num)

How many kinds of sequences are supported by Python? What are they?

Python supports six sequence types, they are:

  1. strings
  2. unicode strings
  3. lists
  4. tuples
  5. buffers
  6. range objects

Explain the shortest way to open a text file and display its contents?

with open("index.txt") as f: s = f.read() print (s)

How to redirect stdout to a file in Python?

You can use shell redirection while executing the python file.

python test.py > output.txt

How to display the contents of text file in reverse order?

The reversed() method returns an iterator that accesses the given sequence in the reverse order.
for line in reversed(list(open("index.txt"))): print(line.rstrip())

Explain what is Dogpile effect? How can you prevent this effect?

The Dogpile effect occurs when cache expires and websites are hit by numerous requests the same time. It is triggered because we allowed more than one request to execute the expensive query.

Dog pile effect can be prevented using semaphore lock. If value expired, first process acquires a lock and starts generating new value. All the subsequent requests check if lock is acquired and serve stale content. After new value is generated, lock is released.