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

Popular posts from this blog

How to format HTML/CSS/JS (or any other) using node.js in Notepad++ in simply easy steps.

Hey guys! Today I am going to tell you on how to use code format / pretty print your HTML / CSS / JS or any other programming language using node modules (Prettier) in notepad++. Before. After. Lets get started! Pre-requisite: you need to have node installed in your computer. You can download it from here . Make sure you have installed node correctly. install notepad++ in your computer. You can download the latest version from here . Step 1. Install Prettier using node. To install Prettier in your system click on Start => cmd. This will open Command prompt. Write this command in Command Prompt.  npm install --save-dev --save-exact prettier To check if prettier is installed correctly type. prettier --check for more info click here. Step 2. Check if nppexec plugin in set in your notepad++ Mostly notepad++ comes with nppexec  by default. Just in case you cannot find nppexec. Check out this amazing blog that tells you step by step how to set up nppexec in your notepad++.  https://www.v

CRUD Operation in SAPUI5. Part 3: Fragments and Update Operation

 CRUD Operation in SAPUI5 Part 3: Fragment and Update Operation We have covered Create and Display operation in our previous article. If you have not checked that I highly recommend you to check that before starting this article for better understanding. Link:  Part 2: Create and Display

CRUD Operation in SAPUI5 Part 2: Create and Display using Input and Table

 CRUD Operation in SAPUI5 Part 2: Create and Display in Table In my previous article we discussed the brief introduction about SAPUI5, MVC architecture and we developed a simple user interface with input and tables. In this article we will discuss the Model and Controller from the MVC architecture. If you have not seen the first part I highly recommend you to see that first. Link:  Part 1: Intro and UI Design