+ 542

Best Python Tips and Tricks

1.Swap: You can swap value of a and b in just one line using: a,b=b,a 2.Reverse a string: my_str="hello" rvrse=my_str[::-1] Output:"olleh" 3.Rotate list by n: l[-n:]+l[:-n] e.g l=[1,2,3,4,5] a=l[-2:]+l[:-2] Output: a=[4, 5, 1, 2, 3] 4.Del all elements of list: lst = [1, 2, 3, 4, 5] del lst[:] Output: lst=[] 5.List comprehension: vals = [expression for value in collection if condition] even_squares = [x * x for x in range(10) if not x % 2] even_squares>>>[0, 4, 16, 36, 64] 6.'==' vs 'is' e.g a = [1, 2, 3] b = a a == b>>>True a is b>>>True But , c = list(a) a==c>>>True a is c>>>False 7.sort() vs sorted: sort() modifies the original list in place. The return value is None. sorted() returns a new list. 8.collections.Counter lets you find the most commonelements in an iterable: E.g; import collections c = collections.Counter('helloworld') c>>>Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1}) c.most_common(3)>>>[('l', 3), ('o', 2), ('e', 1)] 9.Find permutation using itertools. E.g; import itertools for p in itertools.permutations('ABCD'): print(p) Note:itertools.combinations can be used for finding combinations. 10.Importing everything from a module: from <module_name> import * 11.Find factorial by: import math math.factorial(x) P.S. During editing some points were deleted by accident.As I have no saved copy of this it will take some time to find them again.

2nd Apr 2018, 3:50 PM
Mitali
Mitali - avatar
188 Respuestas
+ 186
[Cont.] 12.Boolean is treated as integer: a=[5,4,8,7,1] a[True]>>>4 a[False]>>>5 13.Conversion to binary and hexadecimal: bin(a)>>>binary hex(a)>>>hexadecimal 14.Calendar of any month: import calendar cal = calendar.month(2018,10) 15..Chaining of comparison operator. n = 10 result = 1 < n < 20 print(result)>>>True 16.Use of ternary operators: [on_true] if [expression] else [on_false] x = 10 if (y == 9) else 20 17.Find the most frequent value in a list. test = [1,2,3,4,2,2,3,1,4,4,4] print(max(set(test), key=test.count))>>> 4 18.Create a dictionary from two releated sequences. t1 = (1, 2, 3) t2 = (10, 20, 30) print(dict (zip(t1,t2)))>>>> {1: 10, 2: 20, 3: 30} 19.Transposing a Matrix mat = [[1, 2, 3], [4, 5, 6]] zip(*mat)>>>[(1, 4), (2, 5), (3, 6)] 20. A specialized tool often beats a general purpose tool math.sqrt(x) is more accurate than x ** 0.5 math.log2(x) is more accurate than math.log(x, 2) math.log1p(x) is more accurate than math.log(1+x) 21.If you are using python2 use: from __future__ import print_function It will stop you using print incorrectly in python3. 22.An if ... elif ... elif ... else sequence is a "substitute" for the switch or case statements found in other languages. Tip contributed by Eric Smith :Dictionaries can also be used as a substitute for switch case. 23. The lambda keyword in Python provides a shortcut for declaring small and anonymous functions: e.g add = lambda x, y: x + y add(5, 3)>>>8 24.Try running "import this" ;) 25.Find weekday of a certain date: my_date=datetime.date(1996,7,19) 26.How to merge two dictionaries in Python 3.5+ E.g x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = {**x, **y} z>>>{'c': 4, 'a': 1, 'b': 3}
2nd Apr 2018, 4:06 PM
Mitali
Mitali - avatar
+ 86
don't forget those: a = (5, 6) x, z = a or os.getattr('some attribute', name_of_object) or os.environ[] or print(some _color_encoding + r"") or string.strip() #especially in data output or os.fork() os.execv or if not something or print("%s %r %i %b" % (string,string to repr(),integer,bytes object) or s = [{"hello" : "world"}] print(s[0]["hello"]) or str(subprocess.check_output(some shell,shell=True)) or s = """\ some long string """ I hope this helped :)
10th Apr 2018, 11:41 AM
warlord
warlord - avatar
+ 52
These are all on their separate own good subjects to start from when... making lessons here, if you know what mean 😏
2nd Apr 2018, 4:44 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 40
@Mohammed Ateeb Ali Python Can Be Used In Web Development Have You Ever Heard Of : Flask CherryPy Django CGI Bs4 HTML parser urllib which helps you to do more Interactive stuff with requests,files,downloads,etc HTTP.server or HTTP.client some supported html5 libs in pip
15th Apr 2018, 11:57 AM
warlord
warlord - avatar
+ 39
Cépagrave Yeah But I Will Give Some Examples about Them :)
10th Apr 2018, 12:30 PM
warlord
warlord - avatar
+ 33
@mitali jadhavro Here's Some Examples Note: The Comment Was Very Long That It Tells Me No Connection https://code.sololearn.com/cYmtzJc39BDu/?ref=app
14th Apr 2018, 9:50 AM
warlord
warlord - avatar
+ 28
Hi Mitali ! That's a great and very useful idea you got here ! Here is my suggestion : this thread is in Q&A and will become less visible after a while. And informations here will remain precious for pythonists though. Conclusion : You definitely should make a lesson of it in the lesson factory ! I understand you may feel it's not finished yet, but then it means you can make a multiple-chapters lesson ! I'll be the first happy to go there when I forgot this nice python trick which I know is existing but I don't remember exactly how it goes ... Thanks for your sharing !
8th Apr 2018, 12:22 PM
Cépagrave
Cépagrave - avatar
+ 28
@mitali jadhavrao yes I just saw the post and saw some one or two line examples but I will give more examples 😊
14th Apr 2018, 9:00 AM
warlord
warlord - avatar
+ 25
Python Turtle and multi input codes are now available on Sololearn thanks to an awesome code by Burey!!!🐢 https://www.sololearn.com/post/30301/?ref=app
10th Sep 2018, 12:58 PM
bobbie
bobbie - avatar
+ 21
Amazing information!! 💚 and very helpful for SoloLearn challenges also 😂😂😂 thanks a lot for you help 💚💙
4th Apr 2018, 3:45 PM
Baraa AB
Baraa AB - avatar
+ 20
Cépagrave Hey thanks for the suggestion.I'll definately try to format it...make concepts even more clearer and submit this as a lesson.
8th Apr 2018, 1:29 PM
Mitali
Mitali - avatar
+ 17
[cont.] 27. How to sort a Python dict by value E.g xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1} sorted(xs.items(), key=lambda x: x[1]) >>> [('d', 1), ('c', 2), ('b', 3), ('a', 4)] 28.The "timeit" module lets you measure the execution time of small bits of Python code E.g import timeit timeit.timeit('"-".join(str(n) for n in range(100))',number=10000)>>>0.3412662749997253
8th Apr 2018, 12:04 PM
Mitali
Mitali - avatar
+ 16
Here are some tips and tricks which I came across. 1). You can also print "Hello world!" By using import __hello__ 2).You can Get factorial of any number just by typing import math math.factorial(num) 3). Use set to easily sort a given string in alphabetical order, and given number in the ascending order without repetition in both cases. example = input 1 = dcbadcba ‎output1 = abcd ‎input2 = 432123 ‎output2 = 1234 4). use "try" and "except" statements in very small and simple programs to remove the unnecessary errors. example = import math try: print(math.factorial(int(input()))) except: print("Invalid keyword") it is very helpful if you are a beginner because it boosts confidence that you are tackling errors. And errors are very irritating at the beginning. 5). Use the time module to find out how much time it takes to give output of your code so that you can improve your program to take less time for the output. example = This is the code for Fibonacci number import time def fibo(n): old, new = 0, 1 if n == 0: return 0 for i in range(n-1): old, new = new, old + new return new n = int(input("FIBONACCI OF :")) t1 = time.clock() print("your fibonacci = {} ".format(fibo(n))) t2 = time.clock() print(t2-t1) 6). This is the most useful tip I can give Use comments in codes which are complex to understand it clearly by yourself and it will also take less time to debug which will save your time. 7). Using The "exec" functions you can make 3 liner into one liner Example= a = 2 b = 2 print(a+b) can be written as print(exec("a = 2 \nb = 2\nprint(a+b)")) 8). Use "eval" function to solve integers which are in strings Example = print(eval("4**2")) 9).Bored. Type "import this" to read very interesting tips for coding. And finally the last tip This will help you more than anything. 10). Practice! Practice! And Practice! Thanks for reading!.
11th Apr 2018, 6:31 PM
Salman
Salman - avatar
+ 16
soon I will b studying python and the information here is really helpful. thanks for the effort
12th Apr 2018, 1:24 PM
William Wll Luhanga
William Wll Luhanga - avatar
+ 15
I have few key points... Everyone knows about SET. Let A={1,2,3}, B={2,3,4} For Union, A.union(B) or B.union(A) or A | B Result = {1,2,3,4} For Intersection, A.intersection(B) or B.intersection(A) or A & B Result = {2,3} For Difference, A.difference(B) or A-B Result = {1} B.difference(A) or B-A Result = {4} For symmetric difference, A.symmetric_difference(B) or B.symmetric_difference(A) or A^B Result = {1,4} YOU CAN PLAY WITH MORE PROPERTIES OF SET THEORY... 😃
19th Jan 2019, 1:29 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 14
Eric Smith Excellent.👍 Use of dictionries was very thouthful.👍
4th Apr 2018, 6:20 AM
Mitali
Mitali - avatar
+ 13
Mitali Jadhavrao, Nice compilation. Thanks for sharing and appreciate your efforts on compiling, making example snippets, and posting it here, not like everyone subscribed to real Python or other sources anyways : ) (Edit) also make best answer mark on [Continue] post so it appears on top, easier to read as continuous post.
5th Apr 2018, 2:33 AM
Ipang
+ 13
Very useful information I got which I don't know! !! Thank you very much.
8th Apr 2018, 7:27 AM
💞ⓢⓦⓐⓣⓘ💞
💞ⓢⓦⓐⓣⓘ💞 - avatar
+ 13
Perfect ! That will help many sololearners for sure !
8th Apr 2018, 3:06 PM
Cépagrave
Cépagrave - avatar
+ 13
thanks
2nd Jul 2018, 5:50 AM
Cuthbert Clayton Carrick
Cuthbert Clayton Carrick - avatar