Skip to main content

Python tricks you did not know!



Python is one of the world’s most popular and in demand programming language. There are various reasons being:
  •  It’s super easy
  •  It’s easy to learn, even for beginners
  •  It has large number of modules and libraries.
Here are a few python tricks that I stumbled upon while coding.

1. All or Any

“All” keyword returns true if all the conditions are true, whereas “Any” returns true if any on condition is true.
x = [True, True, False]
if any(x):
    print("At least one True")
if all(x):
    print("Not one False")
if any(x) and not all(x):
    print("At least one True and one False"

2. howdoi

If you forget any keyword or the coding template, you can easily refer without going away from the terminal.

First install howdoi. Make sure you have pip installed for your python version.
$ pip install howdoi
Now ask any questions you have. It scrapes the top answer from StackOverflow and gives you the appropriate answer. For example:
$ howdoi vertical align css
$ howdoi for loop in java
$ howdoi undo commits in git

3. map

Python has various inbuilt features that can write functions. The most popular one is "map" along with the "lambda" function. It's a little tricky but is very useful while writing quick codes.
x = [1, 2, 3]
y = map(lambda x : x + 1 , x)
# prints out [2,3,4]
print(list(y)

4. pprint

"pprint" is just like "print", but the only difference is the extra letter "p" which means pretty. Well, "pprint" helps to tidy your output especially when you use json or xml parsing. It comes very handy and makes it easier to read.
import requests
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)

5. sh

Now just imaging if you are running a python program and suddenly you need to write a "bash" code ( your terminal codes ). This is most exciting stuff about python!
import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')

6. zip

Create your own dictionary from two lists. Possible? yes!
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
zip() is an inbuilt function that tales a number of iterable objects and returns a list of tuples. You can unzip the objects by calling *zip() function. Try it out!

7. Most frequent element in list.

Now rather than going through multiple for loops and multiple initialized variables like you used to do in java or c++, Python provides you in just one line!
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

8. strip

You could remove extra spaces or unwanted special characters from your string using strip() function.
name = "  George "
name_2 = "George///"
name.strip() # prints "George"
name_2.strip("/") # prints "George"

9. enumerate

Iterating over list values while getting the index too. This function returns the mapped list of index and their values.
m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
    print('{0}: {1}'.format(index, value))

10. Reversing string without using reverse!

Is it confusing? Just look at the code and laugh!
a =  "ilovepython" 
print a[::-1]  #output: nohtypevoli
 

Comments