WHAT ARE SOME COOL PYTHON TRICKS?
7 min
Feb 10 2021
What are some cool python tricks
Trick #1 Reversing a string in Python
1. >>> a =  "codementor" 
2. >>> print "Reverse is", a::-1 
3. Reverse is rotnemedoc  
Trick #2 Transposing a Matrix
1. >>> mat = [1, 2, 3, 4, 5, 6] 
2. >>> zip(*mat)(1, 4), (2, 5), (3, 6) 
Trick #3 a = 1,2,3 Store all three values of the list in 3 new variables
1. >>> a = 1, 2, 3 
2. >>> x, y, z = a  
3. >>> x 
4. 1 
5. >>> y 
6. 2 
7. >>> z 
8. 3  
Trick #4 a = "Code", "mentor", "Python", "Developer" Create a single string from all the elements in list above
1. >>> print " ".join(a) 
2. Code mentor Python Developer  
Trick #5 List 1 = 'a', 'b', 'c', 'd' List 2 = 'p', 'q', 'r', 's' Write a Python code to print ap bq cr ds
1. >>> for x, y in zip(list1, list2): 
2. ...    print x, y 
3. ap 
4. bq 
5. cr 
6. ds  
Trick #6 Swap two numbers with one line of code
1. >>> a = 7 
2. >>> b = 5 
3. >>> b, a = a, b 
4. >>> a 
5. 5 
6. >>> b 
7. 7  
Trick #7 Print "codecodecodecode mentormentormentormentormentor" without using loops
1. >>> print "code"*4+' '+"mentor"*5codecodecodecode mentormentormentormentormentor  
Trick #8 a = [1, 2, 3, 4, 5, 6] Convert it to a single list without using any loops Output:- 1, 2, 3, 4, 5, 6
1. >>> import itertools  
2. >>> list(itertools.chain.from_iterable(a))1, 2, 3, 4, 5, 6  
Trick #9 Checking if two words are anagrams
1. def is_anagram(word1, word2):     
2. """Checks whether the words are anagrams.     
3. word1: string     
4. word2: string     
5. returns: boolean"""  
Complete the above method to find if two words are anagrams
1. from collections import Counter 
2. def is_anagram(str1, str2):      
3. return Counter(str1) == Counter(str2)>>> 
is_anagram('abcd','dbca')True>>> 
is_anagram('abcd','dbaa')False  
Trick #10 Taking a string input For example "1 2 3 4" and return 1, 2, 3, 4 Remember the list being returned has integers in it Don't use more than one line of code
1. >>> result = map(lambda x:int(x) ,raw_input().split()) #1 2 3 4 
2. >>> result1, 2, 3, 4 
BLOG LATEST
Popular articles
GOT AN IDEA? LET'S DISCUSS!
Share your project’s scope, timeline, technical requirements, business challenges, and other details you consider necessary. Our team will study them and contact you soon. Let’s make an exciting product together!
By sending this form I confirm that I have read and accept the Privacy Policy
WELCOME TO OUR OFFICES
Georgia
Russia