Last updated 749 days ago

Lifehack

11 Python Hacks Every Developer Should Know

1. Iterating Multiple Lists Professionally

Most of the time when you scrape data from the web, you store it in a different list. This hack lets you print each element of the list corresponding to each element of another list.

2. Slicing For Advantage

Slicing is a built-in feature of python that allows you to access certain parts of a sequence. It can also be used to modify, or delete items from them. There are tons of examples where you can use slicing to reduce the size of code.

”’ Checking For Palindrome ”’

name = “wow”

print(name==name[::-1])

———–

True”’ Retriving Even Numbers From a Natural Sequence ”’

natural_numbers = [1,2,3,4,5,6,7,8,9,10]

even_numbers = natural_numbers[1::2]

print(even_numbers)

————-

[2,4,6,8,10]

3. Use .join instead of + to perform string concatenation

Don’t

my_name = ‘firstname’+ ‘ ‘ + ‘lastname’

Do

my_name = ” “.join([‘firstname’,’lastname’])

4. Use List Comprehension for readable for loops

numbers = [1,2,3,4,5,6,7,8,9,10]

Don’t

even_halves = [ ]

for num in numbers:

   if num%2 == 0:

      even_halves.append(num/2)

print(even_halves)

Do:

even_halves = [num/2 for num in numbers if num%2==0]

7. If you are assigning a value to a variable, use def functions instead of lambda

Save the lambda functions for calculation inside of expressions.

Don’t

squared = lamdba x: x**2

Do

def squared(x):

  return x**2

8. Break those long lines

Pay attention to the text wrap line. Stay Inside your wrap line on the editor.

Don’t

df = pd.read_excel(‘This/extremely/long/file/path/that/extends/ /to/the/next/line/and/screws/with/indentation.xlsx’)

mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20000,30000,3100000320000]

do backslash and implicit continuation:

filepath = “this/sweet/line/” \

          “continued/prettily/”\

          “looksbetter.xlsx”

df = pd.read_excel(filepath)

my_list = [1,2,3,4,5,6,7,8,9,10,11,

         12,13,14,15,16,17,18,19,

         20000,30000,3100000,320000]

if this_happens or that_happens \

  or these_happen:

     print(‘blah’)

else:

  print(‘the other blah’)

9. Trimming Scraped Data

When we scrape some text, heading there is a lot of unwanted text (\t, \n, \t, etc.) also get scraped. Trimming is a way to getting rid of that unwanted data. There is a method in python named strip() that will trim all the scraped data.

————– Trimming A String ———–

data = “\n\n\n \t  David’s Foord and Restaurant \t \n\n\n    “

print(data.strip())

–o/p—–

David’s Foord and Restaurant

——— Trimming List of Strings ———

data = [“\n\n\n Burger \t   “,”\n\t Pizza \t  “]

cleaned_data = [i.strip() for i in data]

print(cleaned_data)

—o/p—-

[“Burger”,”Pizza”]

10. The _ Operator

Single underscore _ is a valid character in python. It can be used as a variable name. It is a special character that is used to store the result of the previous evaluation according to python docs.

———- As a Variable ———–

_ = 10

b = 20

sum = _+b

print(sum)

——

30

———— Restoring The Previous Evaluation Result ——

>>> 200+400

600

>>> _*5

3000

11. Shorter Names

One of the biggest features of python is its vast amount of libraries. The problem comes when you have to use them again and again in your program because some of them have bigger and non-English friendly names. Python offers a simpler way to shorten the name of the library with the help of as keywords.

## Normal Way

import numpy

import speech_recognition

## Shorten Name

import numpy as np

import speech_recognition as sr

Was this article helpful to you? Yes No

How can we help?

Archives

Categories

Looking for help ? Contact Support

Welcome to the documentation page of SassLand. Based on the RTF

Create support ticket