10 Amazing Python Tricks You Should Know

Leave a Comment
These 10 Python programming tricks by Sumit Raj of CodeMentor[1] amazed me:


I’d happily like to share them here by courtesy Sumit Raj:
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)
  3. [(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. ...
  4. a p
  5. b q
  6. c r
  7. d s
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"*5
  2. codecodecodecode 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))
  3. [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
  6. """
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)
  4. >>> is_anagram('abcd','dbca')
  5. True
  6. >>> is_anagram('abcd','dbaa')
  7. False
Trick #10.
Taking a string input.
For example "1 2 3 4" and return [1, 2, 3, 4]
Remember 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())
  2. 1 2 3 4
  3. >>> result
  4. [1, 2, 3, 4]

Footnotes