Sunteți pe pagina 1din 5

1.

difference : open() and with open()


Ans: When you use with statement with open function, you do not need to close the
file at the end, because with would automatically close it for you.
Example:
def foo():
f = open('a.txt','r')
for l in f:
pass
f.close()

def foo1():
with open('a.txt','r') as f:
for l in f:
pass

2. what readlines do? 3. Difference between readline and readlines


Ans:
* read(size) >> size is an optional numeric argument and this func returns a
quantity of data equal to size. If size if omitted, then it reads the entire file
and returns it
* readline() >> reads a single line from file with newline at the end
* readlines() >> returns a list containing all the lines in the file
* xreadlines() >> Returns a generator to loop over every single line in the file

4. How replace function in dictionary works?


example:
dict['foo'] = 123
print "Updated dict['foo']:", dict['foo']

Output:
{'baz': 'Hello', 'foo': 123, 'bar': [1, 2, 3]}

5. What is isinstance?
Returns a Boolean stating whether the object is an instance or subclass of another
object.
Example:
>>> isinstance('foo', basestring)
True
>>> isinstance('foo', float)
False

6. Slicing
The general method format is: slice(start, stop, increment) , and it is analogous
to start:stop:increment when applied to a list or tuple.
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:4:2]
[2, 4]
>>> a[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]

7. List1=[1,2,3]
List2 = [4,5,6]
List1.append(List2) => output? [1,2,3,[4,5,6]]
List1.extends(List2) => output? [1,2,3,4,5,6]

Difference between append & extend?


Ans: append() : It is basically used in python to add, one element.
extend() : Where extend(), is used to merged to lists or insert multiple elements
in one list.
The method "append" adds its parameter as a single element to the list, while
"extend" gets a list and adds its content

8. What is lambda function?


Ans: lambda function is a way to create small anonymous functions
Lambda functions are mainly used in combination with the functions filter(), map()
and reduce().
>>> def f (x): return x**2
>>> print f(8)
64

>>> g = lambda x: x**2


>>> print g(8)
64

9. Difference between py and pyc


When a module is loaded, the py file is "byte compiled" to pyc files.
if no module is in py file there will be no pyc file

.pyc contain the compiled bytecode of Python source files. The Python interpreter
loads .pyc files before .py files, so if they're present,
it can save some time by not having to re-compile the Python source code.

Python is an interpreted language, as opposed to a compiled one, though the


distinction can be blurry because of the presence of the bytecode compiler.
This means that source files can be run directly without explicitly creating an
executable which is then run.

10. Assert & eval -> python unit test concept

11. Map?
Map applies a function to all the items in an input_list
r = map(func, seq)

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

def multiply(x):
return (x*x)
def add(x):
return (x+x)

funcs = [multiply, add]


for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)

# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]

12. reduce?
Reduce is a really useful function for performing some computation on a list and
returning the result.
Examples of reduce()
Determining the maximum of a list of numerical values by using reduce:
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>>
Calculating the sum of the numbers from 1 to 100:
>>> reduce(lambda x, y: x+y, range(1,101))
5050

13. Filter
filter creates a list of elements for which a function returns true
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

# Output: [-5, -4, -3, -2, -1]

14. What is for-else ? whats the use of this?

15. Str = python


I want to print oh only ? how do u print?
>>> str[-2:-4:-1]
'oh'

16. List reverse


ans [::-1]

17. What is GIL (Global Interpreter Lock)? What it do?


In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple
native threads from executing Python bytecodes at once.
This lock is necessary mainly because CPython's memory management is not thread-
safe

18. Args & kargs? (* and **). Where list & dict can pass?

19. What __init__.py do?


20. Namespaces In python?
Namespace is
21. Decorators
22. Generators
23. Iterators
24. Write a program:
List all Directory and subdirectory or folders from given path?
>>> path
'C:\\Users\\inmkharade.ADHARMAN\\Desktop'
>>> dirs = os.listdir(path)
>>> dirs
['11f515b30401b6e9163799569d7bbd39.jpg', 'Adobe Reader XI.lnk', 'bank', 'catwoman-
adimanavdotcom-586x900.jpg', 'Computer - Shortcut.lnk',
'desktop.ini', 'Excels PDF', 'google-adimanavdotcom.jpg', 'images',
'Issue_tracker.txt',
'links.txt', 'log', 'Lync 2013.lnk', 'Monica_CV1.docx (1).docx',
'Monica_Kharade.docx',
'new 1.txt', 'Outlook 2013.lnk', 'P1010530.JPG', 'PPT DOC', 'project',
'PuTTY.lnk',
'pyth prgms', 'python-guide.pdf', 'resume_DiptiKulkarni.pdf',
'SHUBHAM.pdf', 'training', 'VirtG_Preso_16Oct2014_v1.pdf',
'WinSCP.exe', 'WinSCP.ini', '~$Things to buy - Copy.xlsx']

below prgm witll print only subdirectories not files:

import os
def get_immediate_subdirectories(a_dir):
print [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
get_immediate_subdirectories('C:\Users\inmkharade.ADHARMAN\Desktop')

https://hplgit.github.io/edu/ostasks/ostasks.pdf

25. Flatten the dictionary.


{Key1:[1,2,3], Key2:{{key3:23,55}} . Convert dictionary of
dictionary into dictionary
Diffrent example:
>>> a = [{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> a
[{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> {d.pop("id"): d for d in map(dict, a)} #dict is function
here
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}

One more example:


>>> list_key_value = [ [k,v] for k, v in dict.items(data)]
>>> list_key_value
[['Key2', [23, 55]], ['Key1', [1, 2, 3]]]

26. From where Import error will come?


Ans : from sys.module (Read more)

27. Difference between import test and From test import *


28. __new__ when does it call who calls it?
29. Marshalling and unmarshalling ?
30. Pickle and unpickling ?
31. Difference between range and xrange?
32. Mutable & immutable in python?
33. Memory management in Python ?

34. Inheritance in Python classes


35. Call by value or call by reference?
36. Does Python support function overloading n overriding?
37. Python is interpreter or compiler?
Ans: Interpreter
So why pyc file get created ? (Ans: In case of package)
38. Package & module difference
39. Small programs like : prime,reverse string, fibonnaci
40. Str = �I am Harsha�
I what output as �Harsha am I�
(Hint: use split and join to convert string to list and list to
string resp.)

41. union in lists


>>> list1 = list(set(x).union(y))
>>> list1
[1, 2, 3, 4, 5]
>>> list1 = list(set(x).intersection(y))
>>> list1
[3]