-
Notifications
You must be signed in to change notification settings - Fork 93
/
350interview.txt
4415 lines (2800 loc) · 148 KB
/
350interview.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Python Interview Questions and Answers by Pythonlife
1. What is Python? What are the benefits of using Python?
Ans: Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
2. What is PEP 8?
Ans: PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
3. What is pickling and unpickling?
Ans: Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
4. How Python is interpreted?
Ans: Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
5. How memory is managed in Python?
Ans: Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
6. What are the tools that help to find bugs or perform static analysis?
Ans: PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
7. What are Python decorators?
Ans: A Python decorator is a specific change that we make in Python syntax to alter functions easily.
8. What is the difference between list and tuple?
Ans: The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
9. How are arguments passed by value or by reference?
Ans: Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
10. What is Dict and List comprehensions are?
Ans: They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
11. What are the built-in type does python provides?
Ans: There are mutable and Immutable types of Pythons built in types Mutable built-in types
List Sets
Dictionaries Immutable built-in types
Strings Tuples Numbers
12. What is namespace in Python?
Ans: In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
13. What is lambda in Python?
Ans: It is a single expression anonymous function often used as In-line function.
14. Why lambda forms in python does not have statements?
Ans: A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
15. What is pass in Python?
Ans: Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
16. In Python what are iterators?
Ans: In Python, iterators are used to iterate a group of elements, containers like list.
17. What is unit test in Python?
Ans: A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
18. In Python what is slicing?
Ans: A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
19. What are generators in Python?
Ans: The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
20. What is docstring in Python?
Ans: A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.
21. How can you copy an object in Python?
Ans: To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
22. What is negative index in Python?
Ans: Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
23. How you can convert a number to a string?
Ans: In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
24. What is the difference between Xrange and range?
Ans: Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
25. What is module and package in Python?
Ans: In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
26. Mention what are the rules for local and global variables in Python?
Ans: Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
27. How can you share global variables across modules?
Ans: To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
28. Explain how can you make a Python Script executable on Unix?To make a Python Script executable on Unix, you need to do two things,
Ans: Script file’s mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
29. Explain how to delete a file in Python?
Ans: By using a command os.remove (filename) or os.unlink(filename)
30. Explain how can you generate random numbers in Python?
Ans: To generate random numbers in Python, you need to import command as import random
random.random()
This returns a random floating point number in the range [0,1)
31. Explain how can you access a module written in Python from C?
Ans: You can access a module written in Python from C by following method, Module = =PyImport_ImportModule(“”);
32. Mention the use of // operator in Python?
Ans: It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
33. Mention five benefits of using Python?
Ans: Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
Provide easy readability due to use of square brackets Easy-to-learn for beginners
Having the built-in data types saves programming time and effort from declaring variables
34. Mention the use of the split function in Python?
Ans: The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.
35. Explain what is Flask & its benefits?
Ans: Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.
36. Mention what is the difference between Django, Pyramid, and Flask?
Ans: Flask is a “micro framework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
Like Pyramid, Django can also used for larger applications. It includes an ORM.
37. Mention what is Flask-WTF and what are their features?
Ans: Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are
Integration with wtforms Secure form with csrf token Global csrf protection Internationalization integration Recaptcha supporting
File upload that works with Flask Uploads
38. Explain what is the common way for the Flask script to work?
Ans: The common way for the flask script to work is…
Either it should be the import path for your application Or the path to a Python file
39. Explain how you can access sessions in Flask?
Ans: A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
40. Is Flask an MVC model and if yes give an example showing MVC pattern for your application?
Ans: Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example
from flask import Flaskapp = Flask(_name_)
@app.route(“/”)
Def hello():
return “Hello World”
app.run(debug = True)
In this code your,
Configuration part will be
from flask import Flask
app = Flask(_name_)
View part will be
@app.route(“/”)
Def hello():
return “Hello World”
While you model or main part will be
app.run(debug = True)
41. What type of a language is python? Interpreted or Compiled?
Ans: Beginner’s Answer:
Python is an interpreted, interactive, objectoriented programming language.
Expert Answer:
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.
42. What do you mean by python being an “interpreted language”? (Continues from previous question)
Ans: An interpreted languageis a programming languagefor which most of its
implementations execute instructions directly, without previously compiling a program
into machinelanguageinstructions. In context of Python, it means that Python program
runs directly from the source code.
43. What is python’s standard way of identifying a block of code?
Ans: Indentation.
44. Please provide an example implementation of a function called “my_func” that returns the square of a given variable “x”. (Continues from previous question)
Ans:
defmy_func(x):
returnx**2
45. Is python statically typed or dynamically typed?
Ans: Dynamic.
In a statically typed language, the type of variables must be known (and usually
declared) at the point at which it is used. Attempting to use it will be an error. In a
dynamically typed language, objects still have a type, but it is determined at runtime.
You are free to bind names (variables) to different objects with a different type. So long
as you only perform operations valid for the type the interpreter doesn’t care what type
they actually are.
46. Is python strongly typed or weakly typed language?
Ans: Strong.
In a weakly typed language a compiler / interpreter will sometimes change the
type of a variable. For example, in some languages (like JavaScript) you can add
strings to numbers ‘x’ + 3 becomes ‘x3’. This can be a problem because if you have
made a mistake in your program, instead of raising an exception execution will continue
but your variables now have wrong and unexpected values. In a strongly typed
language (like Python) you can’t perform operations inappropriate to the type of the
object attempting to add numbers to strings will fail. Problems like these are easier to
diagnose because the exception is raised at the point where the error occurs rather than
at some other, potentially far removed, place.
47. Create a unicode string in python with the string “This is a test string”?
Ans: some_variable=u’Thisisateststring’
Or
some_variable=u”Thisisateststring”
48. What is the python syntax for switch case statements?
Ans: Python doesn’t support switchcase statements. You can use ifelse statements
for this purpose.
49. What is a lambda statement? Provide an example.
Ans: A lambda statement is used to create new function objects and then return them at
runtime. Example:
my_func=lambdax:x**2
creates a function called my_func that returns the square of the argument
passed.
50.What are the rules for local and global variables in Python?
Ans: If a variable is defined outside function then it is implicitly global. If variable is
assigned new value inside the function means it is local. If we want to make it global we
need to explicitly define it as global. Variable referenced inside the function are implicit
global
51.What is the output of the following program?
Ans:
#!/usr/bin/python
deffun1(a):
print’a:’,a
a=33;
print’locala:’,a
a=100
fun1(a)
print’aoutsidefun1:’,a
Ans. Output:
a:100
locala:33
aoutsidefun1:100
52.What is the output of the following program?
Ans:
#!/usr/bin/python
deffun2():
globalb
print’b:’,b
b=33
print’globalb:’,b
b=100
fun2()
print’boutsidefun2′,b
Ans. Output:
b:100
globalb:33
boutsidefun2:33
53. What is the output of the following program?
Ans:
#!/usr/bin/python
deffoo(x,y):
globala
a=42
x,y=y,x
b=33
b=17
c=100
print(a,b,x,y)
a,b,x,y=1,15,3,4
foo(17,4)
print(a,b,x,y)
Ans.Output:
4217417
421534
54.What is the output of the following program?
Ans:
#!/usr/bin/python
deffoo(x=[]):
x.append(1)
returnx
foo()
foo()
Output:
[1]
[1,1]
55. What is the purpose of #!/usr/bin/pythonon the first line in the above
code? Is there any advantage?
Ans: By specifying #!/usr/bin/pythonyou specify exactly which interpreter will be
used to run the script on a particular system. This is the hardcoded path to the python
interpreter for that particular system. The advantage of this line is that you can use a
specific python version to run your code.
56.What is the output of the following program?
Ans:
list=[‘a’,’b’,’c’,’d’,’e’]
printlist[10]
Ans. Output:
IndexError.Or Error.
57.What is the output of the following program?
Ans:
list=[‘a’,’b’,’c’,’d’,’e’]
printlist[10:]
Ans. Output:
[]
Theabovecodewilloutput[],andwillnotresultinanIndexError.
As one would expect, attempting to access a member of a list using an index that
exceeds the number of members results in an IndexError.
58. What does this list comprehension do:
Ans:
[x**2forxinrange(10)ifx%2==0]
Ans. Creates the following list:
[0,4,16,36,64]
59. Do sets, dictionaries and tuples also support comprehensions?
Ans: Sets and dictionaries support it. However tuples are immutable and have
generators but not comprehensions.
Set Comprehension:
r={xforxinrange(2,101)
ifnotany(x%y==0foryinrange(2,x))}
Dictionary Comprehension:
{i:jfori,jin{1:’a’,2:’b’}.items()}
since
{1:’a’,2:’b’}.items()returnsalistof2-Tuple.iisthefirstelement
oftuplejisthesecond.
60.What are some mutable and immutable datatypes/datastructures in
python?
Ans:
Mutable Types Immutable Types
Dictionary number
List boolean
string
tuple
61.What are generators in Python?
Ans: Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let’s try and build a generator for fibonacci numbers –
## generate fibonacci numbers upto n
def fib(n):
p, q = 0, 1
while(p < n):
yield p
p, q = q, p + q
x = fib(10) # create generator object
## iterating using __next__(), for Python2, use next()
x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error
## iterating using loop
for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8
62.What can you use Python generator functions for?
Ans: One of the reasons to use generator is to make the solution clearer for some kind
of solutions.
The other is to treat results one at a time, avoiding building huge lists of results that you
would process separated anyway.
63.When is not a good time to use python generators?
Ans: Use list instead of generator when:
1 You need to access the data multiple times (i.e. cache the results instead of
recomputing them)
2 You need random access (or any access other than forward sequential order):
3 You need to join strings (which requires two passes over the data)
4 You are using PyPy which sometimes can’t optimize generator code as much
as it can with normal function calls and list manipulations.
64.What’s your preferred text editor?
Ans: Emacs. Any alternate answer leads to instant disqualification of the applicant
65.When should you use generator expressions vs. list comprehensions in Python and vice-versa?
Ans: Iterating over the generator expression or the list comprehension will do the same
thing. However, the list comp will create the entire list in memory first while the
generator expression will create the items on the fly, so you are able to use it for very
large (and also infinite!) sequences.
66. What is a negative index in Python?
Ans: Python arrays and list items can be accessed with positive or negative numbers. A
negative Index accesses the elements from the end of the list counting backwards.
Example:
a=[123]
printa[-3]
printa[-2]
Outputs:
1
2
67. What is the difference between range and xrange functions?
Ans: Range returns a list while xrange returns an xrange object which take the
same memory no matter of the range size. In the first case you have all items already
generated (this can take a lot of time and memory). In Python 3 however, range is
implemented with xrange and you have to explicitly call the list function if you want to
convert it to a list.
68. How can I find methods or attributes of an object in Python?
Ans: Builtin dir() function of Python ,on an instance shows the instance variables as
well as the methods and class attributes defined by the instance’s class and all its base
classes alphabetically. So by any object as argument to dir() we can find all the
methods & attributes of the object’s class
69. What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?
Ans:
pass
70. Do you know what is the difference between lists and tuples? Can you give me an example for their usage?
Ans:
First list are mutable while tuples are not, and second tuples can be hashed e.g.
to be used as keys for dictionaries. As an example of their usage, tuples are used when
the order of the elements in the sequence matters e.g. a geographic coordinates, “list”
of points in a path or route, or set of actions that should be executed in specific order.
Don’t forget that you can use them a dictionary keys. For everything else use lists
71. What is the function of “self”?
Ans:
“Self” is a variable that represents the instance of the object to itself. In most of
the object oriented programming languages, this is passed to the methods as a hidden
parameter that is defined by an object. But, in python it is passed explicitly. It refers to
separate instance of the variable for individual objects. The variables are referred as
“self.xxx”.
72. How is memory managed in Python?
Ans:
Memory management in Python involves a private heap containing all
Python objects and data structures. Interpreter takes care of Python heap and
the programmer has no access to it. The allocation of heap space for Python
objects is done by Python memory manager. The core API of Python provides
some tools for the programmer to code reliable and more robust program. Python
also has a builtin garbage collector which recycles all the unused memory.
The gc module defines functions to enable /disable garbage collector:
gc.enable() Enables automatic garbage collection.
gc.disable()-Disables automatic garbage collection
73. What is __init__.py?
Ans:
It is used to import a module in a directory, which is called package import.
74. Print contents of a file ensuring proper error handling?
Ans:
try:
withopen(‘filename’,’r’)asf:
printf.read()
exceptIOError:
print”Nosuchfileexists”
75 How do we share global variables across modules in Python?
Ans:
We can create a config file and store the entire global variable to be
shared across modules in it. By simply importing config, the entire global variable
defined will be available for use in other modules.
For example I want a, b & c to share between modules.
config.py :
a=0
b=0
c=0
module1.py:
importconfig
config.a=1
config.b=2
config.c=3
print”a,b&resp.are:”,config.a,config.b,config.c
output of module1.py will be
123
76. Does Python support Multithreading?
Ans: Yes
Medium
77. How do I get a list of all files (and directories) in a given directory in Python?
Ans: Following is one possible solution there can be other similar ones:
import os
for dirname,dirnames,filenames in os.walk(‘.’):
#printpathtoallsubdirectoriesfirst.
forsubdirnameindirnames:
printos.path.join(dirname,subdirname)
#printpathtoallfilenames.
forfilenameinfilenames:
printos.path.join(dirname,filename)
#Advancedusage:
#editingthe’dirnames’listwillstopos.walk()fromrecursing
intothere.
if’.git’indirnames:
#don’tgointoany.gitdirectories.
dirnames.remove(‘.git’)
78. How to append to a string in Python?
Ans: The easiest way is to use the += operator. If the string is a list of character, join()
function can also be used.
79. How to convert a string to lowercase in Python?
Ans: use lower() function.
Example:
s=’MYSTRING’
prints.lower()
80. How to convert a string to lowercase in Python?
Ans: Similar to the above question. use upper() function instead.
81. How to check if string A is substring of string B?
Ans: The easiest way is to use the in operator.
>>> ‘abc’ in ‘abcdefg’
True
82. Find all occurrences of a substring in Python
Ans: There is no simple builtin string function that does what you’re looking for, but
you could use the more powerful regular expressions:
>>>[m.start()forminre.finditer(‘test’,’testtesttesttest’)]
[0,5,10,15]//thesearestartingindicesforthestring
83. What is GIL? What does it do?Talk to me about the GIL. How does it impact concurrency in Python? What kinds of applications does it impact more than others?
Ans: Python’s GIL is intended to serialize access to interpreter internals from different
threads. On multicore systems, it means that multiple threads can’t effectively make
use of multiple cores. (If the GIL didn’t lead to this problem, most people wouldn’t care
about the GIL it’s only being raised as an issue because of the increasing prevalence
of multicore systems.)
Note that Python’s GIL is only really an issue for CPython, the reference
implementation. Jython and IronPython don’t have a GIL. As a Python developer, you
don’t generally come across the GIL unless you’re writing a C extension. C extension
writers need to release the GIL when their extensions do blocking I/O, so that other
threads in the Python process get a chance to run.
84. Print the index of a specific item in a list?
Ans: use the index() function
>>>[“foo”,”bar”,”baz”].index(‘bar’)
1
.
85.How do you iterate over a list and pull element indices at the same time?
Ans: You are looking for the enumerate function. It takes each element in a sequence
(like a list) and sticks it’s location right before it. For example:
>>>my_list=[‘a’,’b’,’c’]
>>>list(enumerate(my_list))
[(0,’a’),(1,’b’),(2,’c’)]
Note that enumerate() returns an object to be iterated over, so wrapping it in list() just
helps us see what enumerate() produces.
An example that directly answers the question is given below
my_list=[‘a’,’b’,’c’]
fori,charinenumerate(my_list):
printi,char
The output is:
0a
1b
2c
86. How does Python’s list.sort work at a high level? Is it stable? What’s the runtime?
Ans: In early pythonversions, the sort function implemented a modified version of
quicksort. However, it was deemed unstable and as of 2.3 they switched to using an
adaptive mergesort algorithm.
87. What does the list comprehension do:
Ans:
my_list=[(x,y,z)forxinrange(1,30)foryinrange(x,30)forzin
range(y,30)ifx**2+y**2==z**2]
It creates a list of tuples called my_list, where the first 2 elements are the
perpendicular sides of right angle triangle and the third value ‘z’ is the hypotenuse.
[(3,4,5),(5,12,13),(6,8,10),(7,24,25),(8,15,17),(9,12,15),
(10,24,26),(12,16,20),(15,20,25),(20,21,29)]
88. How can we pass optional or keyword parameters from one function to another in Python?
Ans:
Gather the arguments using the * and ** specifiers in the function’s parameter list. This
gives us positional arguments as a tuple and the keyword arguments as a dictionary.
Then we can pass these arguments while calling another function by using * and **:
deffun1(a,*tup,**keywordArg):
…
keywordArg[‘width’]=’23.3c’
…
Fun2(a,*tup,**keywordArg)
89. Python How do you make a higher order function in Python?
Ans:
A higherorder function accepts one or more functions as input and returns a new
function. Sometimes it is required to use function as data To make high order function ,
we need to import functools module The functools.partial() function is used often for
high order function.
90. What is map?
Ans:
The syntax of map is:
map(aFunction,aSequence)
The first argument is a function to be executed for 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.
91. Tell me a very simple solution to print every other element of this list?
Ans:
L=[0,10,20,30,40,50,60,70,80,90]
L[::2]
92. Are Tuples immutable?
Ans: Yes.
93. Why is not all memory freed when python exits?
Ans: Objects referenced from the global namespaces of Python modules are not
always deallocated when Python exits. This may happen if there are circular
references. There are also certain bits of memory that are allocated by the C library that
are impossible to free (e.g. a tool like the one Purify will complain about these). Python
is, however, aggressive about cleaning up memory on exit and does try to destroy every
single object. If you want to force Python to delete certain things on deallocation, you
can use the at exit module to register one or more exit functions to handle those
deletions.
94. What is Java implementation of Python popularly know?
Ans: Jython.
95. What is used to create unicode strings in Python?
Ans:
Add u before the string.
u ‘mystring’
96. What is a docstring?
Ans:
docstring is the documentation string for a function. It can be accessed by
function_name.__doc__
97. Given the list below remove the repetition of an element.
Ans:
words=[‘one’,’one’,’two’,’three’,’three’,’two’]
A bad solution would be to iterate over the list and checking for copies somehow and
then remove them!
A very good solution would be to use the set type. In a Python set, duplicates are not
allowed.
So, list(set(words)) would remove the duplicates.
98. Print the length of each line in the file ‘file.txt’ not including any
whitespaces at the end of the lines?
Ans:
withopen(“filename.txt”,”r”)asf1:
printlen(f1.readline().rstrip())
rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs
(whitespace characters).
99. What is wrong with the code?
Ans:
func([1,2,3])#explicitlypassinginalist
func() #usingadefaultemptylist
deffunc(n=[]):
#dosomethingwithn
printn
This would result in a NameError. The variable n is local to function func and
can’t be accessesd outside. So, printing it won’t be possible.
100. What does the below mean?
Ans:
s = a + ‘[‘ + b + ‘:’ + c + ‘]’
seems like a string is being concatenated. Nothing much can be said without
knowing types of variables a, b, c. Also, if all of the a, b, c are not of type string,
TypeError would be raised. This is because of the string constants (‘[‘ , ‘]’) used in the
statement.
101. What are Python decorators?
Ans:
A Python decorator is a specific change that we make in Python syntax to alter
functions easily.
102. What is namespace in Python?
Ans:
In Python, every name introduced has a place where it lives and can be hooked
for. This is known as namespace. It is like a box where a variable name is mapped to
the object placed. Whenever the variable is searched out, this box will be searched, to
get corresponding object.
103. Explain the role of repr function.
Ans:
Python can convert any value to a string by making use of two functions repr() or
str(). The str() function returns representations of values which are humanreadable,
while repr() generates representations which can be read by the interpreter. repr()
returns a machinereadable representation of values, suitable for an exec command.
Following code sniipets shows working of repr() & str() :
deffun():
y=2333.3
x=str(y)
z=repr(y)
print”y:”,y
print”str(y):”,x
print”repr(y):”,z
fun()
————-
output
y:2333.3
str(y):2333.3
repr(y):2333.3000000000002
104. What is LIST comprehensions features of Python used for?
Ans:
LIST comprehensions features were introduced in Python version 2.0, it creates
a new list based on existing list. It maps a list into another list by applying a function to
each of the elements of the existing list. List comprehensions creates lists without using
map() , filter() or lambda form.
105. Explain how to copy an object in Python.?
Ans:
There are two ways in which objects can be copied in python. Shallow copy &
Deep copy. Shallow copies duplicate as minute as possible whereas Deep copies
duplicate everything. If a is object to be copied then …
copy.copy(a) returns a shallow copy of a.