-
Notifications
You must be signed in to change notification settings - Fork 0
/
PythonTipsTricks.txt
executable file
·1450 lines (1097 loc) · 50.8 KB
/
PythonTipsTricks.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
0. Print
1. Why use main in Python
2. Multiline Comments
3. Exponentiation
4. Python String Formatting
5. Accessing Elelemt in a String Array and SLICING of String:
6. String Builtin Helper Functions
6b. Check if string has only alphabets
7. Printing String
8. Get input from Console
9. Single quotes vs. double quotes in Python
10. What is the difference between tuples and lists in Python?
10a. TUPLES
11. Python Dictionary
Iterating over dictionaries using 'for' loops
11a. Dictionary with mutiple keys having different values
11b. Ordered Dictionary
11c. I'm getting Key error in python
12. How will you convert a string to an int in python?
How will you convert a string to a long in python?
How will you convert a string to a float in python?
How will you convert a object to a string in python?
How will you convert a object to a regular expression in python?
How will you convert a String to an object in python?
How will you convert a string to a tuple in python?
How will you convert a string to a list in python?
How will you convert a string to a set in python?
How will you create a dictionary using tuples in python?
How to split a string by a character
How do you check if a string contains only numbers
Most elegant way to check if the string is empty in Python?
13. Date Time
14. Boolean
15. Function
16. Import Module from Function
17. The __doc__ attribute
18. Variable number of args to a function
19. Lists
20. DICTIONARY:
20a. Sort a dictionary based on values OR keys
21. PYTHON FOR STATEMENT
21b. Accessing the index in Python for loops
22. TYPE of Object:
23. CONTINUATION CHAR:
24. What is GIL Global Interpreter Lock?
25. Creating 2D Array in Python
26. Python Objects: Mutable vs. Immutable
26b. Aren't Python strings immutable
26c. Why are Python strings immutable
27. How do I pass a variable by reference
28. Directory Operations
29. Shebang line First line in python
30. How would you make a comma-separated string from a list
31. Return multiple values from a function
32. __doc__ attribute
33. What is Duck Typing
34. Python CLASSes
34a. Python type class and metaclass
34a1. How to create 'type' class
34b. Python Class Static Variable and Class Variable
34c. Static Methods
35. Python Inheritence and Polymorphism
36. Python Multiple Inheritence
37. Sort a list
38. '//' operator
39. What are the options to clone or copy a list in Python?
40. Check if a number is in range
41. Get arguments from command line
42. Prefix a number with leading zeroes
43. Python integer incrementing with ++
44. Get random number
45. Get eof and offset in a file
46. Default arguments to a function
47. Get path from open file in Python
48. How to copy directory recursively in python and overwrite all?
49. How do I copy a file in python?
50. Maximum and Minimum values for ints
51. Get all files in a directory recursively
52. Touch using Python
53. Platform independent file locking
54. Python `if x is not None` or `if not x is None`?
55. What does the ¿yield¿ keyword do?
56. Ignore hidden files using os.listdir()
57. Generating Discrete random variables with specified weights using SciPy or NumPy
58. How to remove item from a python list if a condition is True? [duplicate]
59. How do I list all files of a directory?
60. list index out of range error using random.choice
61. Convert generator object to list for debugging [duplicate]
62. Python AttributeError: Object has no attribute
63. How to randomly select an item from a list?
64. double equals vs is in python [duplicate]
65. Is it possible only to declare a variable without assigning any value in Python?
66. In Python how should I test if a variable is None, True or False
67. Install pip for multiple versions of Python
68. Singleton in Python
69. When to use self in Python
70. Setting up Pyenv
----------------------------------------------------------------------------------------------
0.
Print
http://stackoverflow.com/questions/12032214/python-3-print-new-output-on-same-line
print "There are %d items in the suitcase." % (list_length)
PYTHON 3.x
DON'T USE + for concatenation
print('My name is', os.getlogin(), 'and I am', 42) --> Works
print('My age is: ' + 42) --> Fails with TypeError: can only concatenate str (not "int") to str
From help(print):
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
You can use the end keyword:
>>> for i in range(1, 11):
... print(i, end='')
...
12345678910>>>
PYTHON 2.x
# Extra comma at end makes sure that it gets printed on the same line
for elmt in range(len(myList)):
print(myList[index] , ","),
1.
Why use main in Python
http://stackoverflow.com/questions/419163/what-does-if-name-main-do
http://stackoverflow.com/questions/4041238/why-use-def-main
def main():
print("hello")
if __name__ == "__main__":
main()
If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__".
If this file is being imported from another module, __name__ will be set to the module's name.
IMP:
Your code can also be imported and used in another module.
By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
Now, if you invoke the interpreter as
python one.py
The output will be
top-level in one.py
one.py is being run directly
If you run two.py instead:
python two.py
You get
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
Thus, when module one gets loaded, its __name__ equals "one" instead of __main__
2.
Multiline Comments
""" hello
world """
Single Line comments
#
3.
Exponentiation
**
pow(10, 2) = 10 ** 2
4.
Python String Formatting
https://docs.python.org/2/library/stdtypes.html#string-formatting
"%0.2f" % (num,)
- Precision (optional), given as a '.' (dot) followed by the precision.
If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
- Length modifier (optional).
- Conversion type.
5.
Accessing Elelemt in a String Array and SLICING of String:
fifth_letter = "MONTY"[4]
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
6.
String Builtin Helper Functions
Methods that use dot notation only work with strings.
On the other hand, len() and str() can work on other data types.
len(str)
str.upper()
str.lower()
str(numeric_value)
How will you capitalizes first letter of string?
capitalize() - Capitalizes first letter of string.
6b.
Check if string has only alphabets
str.isalpha()
6c.
Check if a string is present in another string
http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method?rq=1
if "blah" not in somestring:
continue
6d.
Compare two strings == vs 'is'
The is keyword is a test for object identity while == is a value comparison
If you use is, the result will be true if and only if the object is the same object.
However, == will be true any time the values of the object are the same.
6e.
Strip '\n' from a string
newLine = lines[0].rstrip('\n')
6f.
String leading whitespace from a string
newLine = lines[0].lstrip().rstrip('\n')
6g. How to strip a specific word from a string?
https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
>>> papa = "papa is a good man"
>>> app = "app is important"
>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'
Alternatively use re and use regular expressions. This will allow the removal of leading/trailing spaces.
>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'
7.
Printing String
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
- You need the same number of %s terms in a string as the number of variables in parentheses
8.
Get input from Console
http://stackoverflow.com/questions/954834/how-do-i-use-raw-input-in-python-3
PYTHON 3.x : input()
PYTHON 2.x : raw_input()
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
9.
Single quotes vs. double quotes in Python
http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python
http://henry.precheur.org/python/python_quote.html
Quoting the official docs at https://docs.python.org/2.0/ref/strings.html:
In plain English: String literals can be enclosed in matching single quotes (') or double quotes (").
So there is no difference
I like to use double quotes around strings that are used for interpolation or that are natural language messages, and
single quotes for small symbol-like strings, but will break the rules if the strings contain quotes
Python interpreter is doing when printing string representation:
If the string doesnt contain quotes, it will enclose this string with single quotes.
If the string contains single quotes but no double quotes, it will enclose the string with double quotes.
And if the string contains both single and double quotes, it will use single quotes
10.
What is the difference between tuples and lists in Python?
http://www.tutorialspoint.com/python/python_interview_questions.htm
https://stackoverflow.com/questions/1708510/python-list-vs-tuple-when-to-use-each
Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.
You can't add elements to a tuple. Tuples have no append or extend method.
You can't remove elements from a tuple. Tuples have no remove or pop method.
You can find elements in a tuple, since this doesn¿t change the tuple.
You can also use the in operator to check if an element exists in the tuple.
Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.
It makes your code safer if you ¿write-protect¿ data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.
Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.
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.
10a.
TUPLES
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing ¿
tup1 = ();
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples
11.
Python Dictionary
http://www.tutorialspoint.com/python/python_interview_questions.htm
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.
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
dict.keys()
dict.values()
Iterating over dictionaries using 'for' loops
key is just a variable name.
for key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
For Python 2.x:
for key, value in d.iteritems():
For Python 3.x:
for key, value in d.items():
20.
DICTIONARY:
- Dictornaries are MUTABLE
A dictionary is similar to a list, but you access values by looking up a key instead of an index.
A key can be any string or number.
Dictionaries are enclosed in curly braces
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
str(len(menu))
del menu[key_name]
IT CAN STORE DIFFERENT DATA TYPES
my_dict = {
"fish": ["c", "a", "r", "p"],
"cash": -4483,
"luck": "good"
}
print my_dict["fish"][0]
PRINT
d = {"foo" : "bar"}
for key in d:
print d[key] # IMP
prices = {"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3}
stock = {"banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15}
for item in prices:
print item
print "price: %s" % prices[item]
print "stock: %s" % stock[item]
20a.
Sort a dictionary based on values OR keys
http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value?rq=1
As simple as: sorted(dict1, key=dict1.get)
It is not possible to sort a dict, only to get a representation of a dict that is sorted.
Dicts are inherently orderless, but other types, such as lists and tuples, are not.
So you need a sorted representation, which will be a listprobably a list of tuples.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple.
dict(sorted_x) == x.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
11a.
Dictionary with mutiple keys having different values
https://stackoverflow.com/questions/10664856/make-dictionary-with-duplicate-keys-in-python
Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.
One easy way to achieve this is by using defaultdict:
from collections import defaultdict
data_dict = defaultdict(list)
All you have to do is replace
data_dict[regNumber] = details
with
data_dict[regNumber].append(details)
and you'll get a dictionary of lists.
11b.
Ordered Dictionary
http://stackoverflow.com/questions/1867861/python-dictionary-keep-keys-values-in-same-order-as-declared
>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionary['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])
11c. I'm getting Key error in python
A KeyError generally means the key doesn't exist.
12.
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 to split a string by a character
x.split(¿,¿)
How do you check if a string contains only numbers
Use str.isdigit:
>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>
Most elegant way to check if the string is empty in Python?
if not myString:
13.
Date Time
from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
import time
print time.strftime("%Y-%m-%d %H:%M")
14.
Boolean
True, False have CAP 'T' and CAP 'F'
15.
Function
Python function gets executed only when called
16.
Import Module from Function
Can import just a module from a function
import math
math.sqrt(25)
from math import *
sqrt(25)
17.
The __doc__ attribute
https://www.iram.fr/IRAMFR/GILDAS/doc/html/gildas-python-html/node9.html
Each Python object (functions, classes, variables,...) provides (if programmer has filled it) a short documentation which describes its features.
You can access it with commands like print myobject.__doc__
18.
Variable number of args to a function
http://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2,3)
I was called with 3 arguments: (1, 2, 3)
def biggest_number(*args):
print max(args)
return max(args)
biggest_number(-10, -5, 5, 10)
19.
Lists
Create
odds = [1, 3, 5, 7]
Add Elements
- use append()
SLICING:
LAST INDEX DOES NOT GET INCLUDED
Then, we take a subsection and store it in the slice list.
We start at the index before the colon and continue up to BUT NOT INCLUDING THE INDEX AFTER THE COLON.
SEARCH:
.index()
INSERT:
.insert()
SORT:
.sort()
inventory['backpack'].sort()
REMOVE
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')
inventory['backpack'].remove('dagger')
21.
PYTHON FOR STATEMENT
- IMP: for statement MUST NOT have '(' ')'
for iterating_var in sequence:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
21b.
Accessing the index in Python for loops
http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops
METHOD 1:
for idx, val in enumerate(ints):
print(idx, val)
METHOD 2:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
22.
TYPE of Object:
type()
23.
CONTINUATION CHAR:
The \ character is a continuation character. The following line is considered a continuation of the current line.
24.
What is GIL Global Interpreter Lock?
http://stackoverflow.com/questions/265687/why-the-global-interpreter-lock
http://stackoverflow.com/questions/1294382/what-is-a-global-interpreter-lock-gil
Python's GIL is intended to serialize access to interpreter internals from different threads.
On multi-core systems, it means that multiple threads can't effectively make use of multiple cores.
In general, for any thread safety problem you will need to protect your internal data structures with locks. This can be done with various levels of granularity.
You can use fine-grained locking, where every separate structure has its own lock.
You can use coarse-grained locking where one lock protects everything (the GIL approach).
There are various pros and cons of each method.
Fine-grained locking allows greater parallelism - two threads can execute in parallel when they don't share any resources.
However there is a much larger administrative overhead. For every line of code, you may need to acquire and release several locks.
The coarse grained approach is the opposite.
Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping.
Ultimately it comes down to a tradeoff between single-threaded speed and parallelism.
25.
Creating 2D Array in Python
board[0] = ["O"] * 5
board[1] = ["O"] * 5
board[2] = ["O"] * 5
board[3] = ["O"] * 5
board[4] = ["O"] * 5
print board
board = []
for x in range(5):
tmpList = ["O"] * 5
board.append(tmpList)
print board
26.
Python Objects: Mutable vs. Immutable
https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/
The following are immutable objects:
Numeric types: int, float, complex
string
tuple
frozen set
bytes
The following objects are mutable:
list
dict
set
byte array
26b.
Aren't Python strings immutable
http://stackoverflow.com/questions/9097994/arent-python-strings-immutable
a = "Dog"
b = "eats"
c = "treats"
print a, b, c
# Dog eats treats
print a
# Dog
a = a + " " + b + " " + c
print a
# Dog eats treats
First a pointed to the string "Dog".
Then you changed the variable a to point at a new string "Dog eats treats".
You didn't actually mutate the string "Dog".
Strings are immutable, variables can point at whatever they want.
26c.
Why are Python strings immutable
http://stackoverflow.com/questions/8680080/why-are-python-strings-immutable-best-practices-for-using-them
- Immutable objects are automatically threadsafe.
When you receive a string, you'll be sure that it stays the same.
Suppose that you'd construct a Foo as below with a string argument, and would then modify the string; then the Foo's name would suddenly change:
class Foo(object):
def __init__(self, name):
self.name = name
name = "Hello"
foo = Foo(name)
name[0] = "J"
- With mutable strings, you'd have to make copies all the time to prevent bad things from happening.
- It also allows the convenience that a single character is no different from a string of length one, so all string operators apply to characters as well.
IMP:
And lastly, if strings weren't immutable, you couldn't reliably use them as keys in a dict, since their hash value might suddenly change.
As for programming with immutable strings, just get used to treating them the same way you treat numbers: as values, not as objects.
Changing the first letter of name would be
name = "J" + name[1:]
27.
How do I pass a variable by reference
http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
ANS: pass by assignment
IMP:
When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object. In your example:
self.variable = 'Original'
self.Change(self.variable)
def Change(self, var):
var = 'Changed'
self.variable is a reference to the string object 'Original'.
When you call Change you create a second reference var to the object.
Inside the function you reassign the reference var to a different string object 'Changed', but the reference self.variable is separate and does not change.
The only way around this is to pass a mutable object.
Because both references refer to the same object, any changes to the object are reflected in both places.
self.variable = ['Original']
self.Change(self.variable)
def Change(self, var):
var[0] = 'Changed'
------
Think of stuff being passed by assignment instead of by reference/by value.
That way, it is allways clear, what is happening as long as you understand what happens during normal assignment.
So, when passing a list to a function/method, the list is assigned to the parameter name.
Appending to the list will result in the list being modified.
Reassigning the list inside the function will not change the original list, since:
a = [1, 2, 3]
b = a
b.append(4)
b = ['a', 'b']
print a, b # prints [1, 2, 3, 4] ['a', 'b']
28.
Directory Operations
1. Performing Shell Operations
http://stackoverflow.com/questions/18962785/oserror-errno-2-no-such-file-or-directory-while-using-python-subprocess-in-dj
2. Changing a Directory
from subprocess import call
os.chdir("/Users/pragadh/PRAGADH/DEV/Algos")
print(os.getcwd())
call(["git status"], shell=True)
3. Getting pwd
import os
myPwd = os.getcwd()
29.
Shebang line First line in python
#! /usr/bin/env
#! /usr/bin/env python
In order to run the python script, we need to tell the shell three things:
1.That the file is a script
2. Which interpreter we want to execute the script
3. The path of said interpreter
The shebang #! accomplishes (1.).
The shebang begins with a # because the # character is a comment marker in many scripting languages.
The contents of the shebang line are therefore automatically ignored by the interpreter.
The env command accomplishes (2.) and (3.).
If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH.
The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.
30.
How would you make a comma-separated string from a list
http://stackoverflow.com/questions/44778/how-would-you-make-a-comma-separated-string-from-a-list
myList = ['a','b','c','d']
myString = ",".join(myList )
This won't work if the list contains numbers.
If it contains non-string types (such as integers, floats, bools, None) then do:
myList = ','.join(map(str, myList))
31.
Return multiple values from a function
https://www.mantidproject.org/Working_With_Functions:_Return_Values
1. Get in the form of tuple
def square(x,y):
return x*x, y*y
t = square(2,3)
print(t) # Produces (4,9)
2.
def square(x,y):
return x*x, y*y
xsq, ysq = square(2,3)
print(xsq) # Prints 4
print(ysq) # Prints 9
Just return what you want from the function
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
32. __doc__ attribute
There is a __doc__ attribute for every object.
It prints details about the data type
print(myStr.__doc__)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
33.
What is Duck Typing
http://stackoverflow.com/questions/4205130/what-is-duck-typing
34.
Python CLASSes
https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/
34a. Python type class and metaclass
https://www.pythontutorial.net/python-oop/python-type-class/
https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses
A metaclass is a class that creates other classes. By default, Python uses the type metaclass to create other classes.
type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass.
In the below case:
- x is an instance of class Foo.
- Foo is an instance of the type metaclass.
- type is also an instance of the type metaclass, so it is an instance of itself.
Remember that, in Python, everything is an object. Classes are objects as well. As a result, a class must have a type
>>> class Foo:
... pass
...
>>> x = Foo()
>>> type(x)
<class '__main__.Foo'>
>>> type(Foo)
<class 'type'>
The type of x is class Foo, as you would expect. But the type of Foo, the class itself, is type. In general, the type of any new-style class is type.
34a1. How to create 'type' class
https://realpython.com/python-metaclasses/
You can also call type() with three arguments¿type(<name>, <bases>, <dct>):
- <name> specifies the class name. This becomes the __name__ attribute of the class.
- <bases> specifies a tuple of the base classes from which the class inherits. This becomes the __bases__ attribute of the class.
- <dct> specifies a namespace dictionary containing definitions for the class body. This becomes the __dict__ attribute of the class.
Calling type() in this manner creates a new instance of the type metaclass. In other words, it dynamically creates a new class.
https://stackoverflow.com/questions/22609272/python-typename-bases-dict
NICE EXPLANATION
When you define a class:
class Foo(Base1, Base2):
bar = 'baz'
def spam(self):
return 'ham'
Python essentially does this:
def spam(self):
return 'ham'
body = {'bar': 'baz', 'spam': spam}
Foo = type('Foo', (Base1, Base2), body)
where Foo is then added to the namespace the class statement was defined in.
The block under the class statement is executed as if it was a function with no arguments and the resulting local namespace (a dictionary) forms the class body; in this case a dictionary with 'bar' and 'spam' keys is formed.
You can achieve the same result by passing a name string, a tuple of base classes and a dictionary with string keys to the type() function.
34b.
Python Class Static Variable and Class Variable
http://stackoverflow.com/questions/9056957/correct-way-to-define-class-variables-in-python
- Elements outside the __init__ method are static elements.
It means, they belong to the class.
- Elements inside the __init__ method are elements of the object (self).
They don't belong to the class.
You'll see it more clearly with some code:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
34c.
Static Methods
https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/
There is a class of methods, called static methods, that don't have access to self.
They are methods that work without requiring an instance to be present.
Since instances are always referenced through self, static methods have no self parameter.
The following would be a valid static method on the Car class:
class Car(object):
...
def make_car_sound():
print 'VRooooommmm!'