Top 10 Useful Python Tricks For Beginners

Useful Python Tricks a Beginner Should Know

Trick #1

Swapping strings without additional variable.

>>> a = "PYTHON"

>>> b = "LOVERS"

>>> a,b = b,a

>>> print a

"LOVERS"

>>>print b

"PYTHON"

Trick #2

Reversing a string in python

>>> p = "PYTHONLOVERS"

>>>print "Reverse is",p[ : :-1 ]

Reverse is SREVOLNOHTYP

Trick #3

Joining strings

Create a single list from all the elements in the list below

p = ["PYTHON", "LOVERS",  "IS", "THE", "BEST"]

After:

>>>print "".join(p)

PYTHON LOVERS IS THE BEST

Trick #4

list1 = [‘a’, ‘b’, ‘c’, ‘d’]
list2 = [‘p’, ‘q’, ‘r’, ‘s’]
Write a Python code to print
ap
bq
cr
ds
>>> for x, y in zip(list1,list2):
...    print x, y
...
a p
b q
c r
d s

Trick #5

print”pythonpythonpython loversloverslovers”

>>>print "python"*3+' +"lovers"*3

pythonoythonpython loversloverslovers

Trick #6

a = [[1, 2], [3, 4], [5, 6]]
Convert it to a single list without using any loops.
Output:- [1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]

Trick #7

Checking if two words are anagrams
def is_anagram(word1, word2):
"""Checks whether the words are anagrams. word1: string word2: string returns: boolean """

from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
>>> is_anagram('abcd','dbca')
True
>>> is_anagram('abcd','dbaa')
False

Trick #8

 Permutations (itertools.permutations)

>>> for p in itertools.permutations([1, 2, 3, 4]):
...     print ''.join(str(x) for x in p)
...
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

Trick #9

Transposing a Matrix

>>> mat = [[1, 2, 3], [4, 5, 6]]
>>> zip(*mat)
[(1, 4), (2, 5), (3, 6)]

Trick #10

Take 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

>>> result = map(lambda x:int(x) ,raw_input().split())
1 2 3 4
>>> result
[1, 2, 3, 4]

                             #STAY TUNED FOR MORE PYTHON TRICKS

 

You May Like :-

 

 

 

6 Comments

  1. Fabrizio April 10, 2016
    • mualusidiego April 10, 2016
  2. Kamal Thakur April 10, 2016
  3. DeepSpace April 10, 2016
    • Kamal Thakur April 10, 2016
  4. Some Name May 13, 2016