paint-brush
Python Tricks Every Developer Should Knowby@kalebujordan
1,336 reads
1,336 reads

Python Tricks Every Developer Should Know

by Kalebu Jordan October 16th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Python is one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler? In this tutorial, you’re going to learn a variety of Python tricks that you can use to write Python code in a more readable and efficient way like a pro. You will be surprised by seeing Zen of Writing Python code pop up in front of you when you do this, You can easily reverse your string with just a bit of slicing.
featured image - Python Tricks Every Developer Should Know
Kalebu Jordan  HackerNoon profile picture

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

Create a single string from all elements in the list

Instead of Iterating each element over the list using for loop and appending each element to the string, you can do this instead.

>>> python = ["Python", "Syntax" , "is", "elegantly"]
>>> python_string = ' '.join(python)
>>> print(python_string)
    Python Syntax is elegantly

Merging two dictionaries

Use update( ) to combine two sets of dictionaries

>>> a = {"name":"Python", "creator":"Guido"}
>>> b = {"age": 30, "gender" : None}
>>> a.update(b)
>>> print(a)
{'gender': None, 'age': 30, 'name': 'Python', 'creator': 'Guido'}

List comprehension to create a specific list

Use List Comprehension instead of for loop on a case where you want to create a list from a sequence with certain criteria.

You’re going to specify the criteria. For instance in the example below we have created a list of odd numbers in just one line of code (one-liner).

>>> odd = [x for x in range(20) if x%2 != 0]
>>> print(odd)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Reversing a string in Python

You can easily reverse your string with just a bit of slicing as shown below.

>>> quote = "doog si doG"
>>> print(quote[::-1])
God is good

Unpacking a Python List

Instead of or reassigning each variable to index in a list, you do this at once by unpacking them as shown in the code below.

>>> names = ['Melisa', 'Lisa', 'Peace']
>>> niece, friend, crush = names
>>> print('{} {} {}'.format(niece, friend, crush))
Melisa Lisa Peace

Iterating over two python list

You can actually Iterate over two lists at once without using nested for a loop as shown below

>>> books = ['mabala', 'money heist', 'GOT']
>>> pages = [200, 300, 600]
>>> for book ,page in zip(books, pages):
...     print("{}--->{}".format(book, page))
... 
mabala--->200
money heist--->300
GOT--->600

Using all or any in a conditional statement

Instead of writing many if-else statements for your logic, you can actually do this using any and all keywords.

all will evaluate to True only if all elements are true while any will evaluate to True if any of the multiple conditions evaluate to True.

>>> data = [True, True, False]
>>> if any(data):
...     print("at least")
... 
at least
>>> if not all(data):
...     print("Thats right")
... 
That's right

Cumulative summing a sequence of numbers

In case you want the cumulative sum of numbers to do some plotting, you can easily do this using numpy using its cumsum () function

>>> import numpy as np
>>> factors = list(np.cumsum(range(0,20,3)))
>>> print(factors)
[0, 3, 9, 18, 30, 45, 63]

Adding Index to Iterables(list, tuples, etc..)

Do this to automatically index your elements within an Iterable

>>> students = ['Immaculate', 'Prisca', 'Lizy']
>>> student_with_index = list(enumerate(students))
>>> print(student_with_index)
[(0, 'Immaculate'), (1, 'Prisca'), (2, 'Lizy')]

import this (Python design principles)

One you do this, You will be surprised by seeing Zen of Writing Python code pop up in front of you

import this 
'''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''

Hope you find this post interesting, Now share the with your fellow peers that you have made it, Tweet now.

The Original Article can be found on kalebujordan.com