 Best Python Tips and Tricks | Sololearn: Learn to code for FREE!

+503

# 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.

+173

[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}

+82

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["hello"]) or str(subprocess.check_output(some shell,shell=True)) or s = """\ some long string """ I hope this helped :)

+49

These are all on their separate own good subjects to start from when... making lessons here, if you know what mean 😏

+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

+39

Cépagrave Yeah But I Will Give Some Examples about Them :)

+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

+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 !

+28

@mitali jadhavrao yes I just saw the post and saw some one or two line examples but I will give more examples 😊

+24

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

+21

Amazing information!! 💚 and very helpful for SoloLearn challenges also 😂😂😂 thanks a lot for you help 💚💙

+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.

+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) >>> [('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

+16

+16

soon I will b studying python and the information here is really helpful. thanks for the effort

+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... 😃

+14

Eric Smith Excellent.👍 Use of dictionries was very thouthful.👍

+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.

+13

Very useful information I got which I don't know! !! Thank you very much.

+13

Perfect ! That will help many sololearners for sure !