30 Top Python tricks and Tips with Code Examples for Efficient Coding

Posted in /  

30 Top Python tricks and Tips with Code Examples for Efficient Coding
vinaykhatri

Vinay Khatri
Last updated on May 30, 2024

    As compared to other high-level programming languages, Python has unique and easy-to-learn syntax. Unlike other programming languages, Python does not use curly brackets and semicolons; instead, it uses indentation, which makes code more readable. Python has many inbuilt and third-party libraries, which makes Python the most versatile programming language . It also contains many tricks which come in very handy while writing code. Python developers often use these tricks to increase the readability of code and keep the length of the code short.

    Python Tricks & Tips To Enhance your Coding Efficiency

    Here in this article, we have provided some of the most important Python tips and tricks. If you want to set a career in Python development, you can add these tricks to your python skill inventory.

    1. SWAP two Numbers

    ten = 10
    hundred = 100
    ten, hundred = hundred, ten       # swapping hundred with ten
    print("hundred is:",hundred)
    print("ten is:", ten)

    Output:

    hundred is: 10
    ten is: 100

    Note: In other programming languages such as Java and C++ , we need a temporary variable to swap two numbers in, but we can do it without a temporary variable .

    2. Convert a string into a list

    string = "TechGeekBuzz"
    print(list(string))

    Output:

    ['T', 'e', 'c', 'h', 'G', 'e', 'e', 'k', 'B', 'u', 'z', 'z']

    3. Reverse a String

    string = "TechGeekBuzz"
    print(string[ : :-1])

    Output:

    zzuBkeeGhceT

    4. Create a string from a list

    my_list = ['this', "is", "an", "article","from", "TechGeekBuzz"]
    print("-".join(my_list))

    Output:

    this-is-an-article-from-TechGeekBuzz

    5. To print the path of the imported library

    import django
    print(django)

    Output:

    <module 'django' from 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\django\\__init__.py'>

    6. Combine two iterable corresponding with their index value.

    a = ['one', 'two','three']
    b = [1 , 2 , 3 ]
    c= zip(a,b)
    print(list(c))

    Output:

    [('one', 1), ('two', 2), ('three', 3)]

    7. Get the maximum from an iterable

    my_list = [1, 2, 3,200,12,342]
    print("Max is:", max(my_list))
    print("Minimum value is:",min(my_list))

    Output:

    Max is: 342
    Minimum value is: 1

    8. To get the index value of an element

    my_list = [1, 2, 3,200,12,342]
    print("Index value of 200:", my_list.index(200))

    Output:

    Index value of 200: 3

    9. If else statement in one line

    print("TechGeekbuzz") if True else print("Thanks")

    Output:

    TechGeekbuzz

    10. Python List Comprehension

    cube = [x ** 3 for x in range(10)]
    print(cube)

    Output:

    [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

    11. Set comprehension

    cube = {x ** 3 for x in range(10)}
    print(cube)

    Output

    {0, 1, 64, 512, 8, 343, 216, 729, 27, 125}

    Note: Unlike list, the set does not store its element in contagious memory location

    12. Dictionary Comprehension

    cube = {x:x ** 3 for x in range(10)}
    print(cube)

    Output:

    {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729} 

    13. Generators Comprehension

    cube = (x ** 3 for x in range(10))
    print(cube)

    Output:

    <generator object <genexpr> at 0x031E9568>

    14. Execute a command written in string

    string = 'print("The sum of 2+3 is:", 2+3)'
    eval(string)

    Output:

    The sum of 2+3 is: 5

    15. Get the Size of an Object

    import sys
    a= 100
    print(sys.getsizeof(a))

    Output:

    14

    16. Print a string n time

    string = "Hello World!"
    print(string * 8)

    Output:

    Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!

    17. Make a list of length 1 to length n

    my_list = [0]
    my_list *=10
    print(my_list)

    Output:

    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    18. Create a list up to N even numbers

    n= 20
    my_list = list(range(0,n,2))
    print(my_list)

    Output:

    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

    19. Flatten a List in Python

    import itertools
    matrix = [[1, 2,3], [4,5,6], [7,8,9]]
    flat_list = list(itertools.chain.from_iterable(matrix))
    print(flat_list)

    Output

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

    20. Find the most common item from a list

    age = [15, 16, 15, 17, 17, 16, 16, 15, 17, 18, 14, 17 ,15]
    most_common =max(age, key = age.count)
    print("The most common age is: ", most_common)

    Output

    The most common age is:  15

    21. List out all the substrings of a string

    main = "hello"
    
    substrings = [main[i: j] for i in range(len(main)) for j in range(i + 1, len(main) + 1)]
    
    print(substrings)

    Output

    ['h', 'he', 'hel', 'hell', 'hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o']

    22. Print a string multiple times

    #print hello five times
    print("Hello "*5)

    Output

    Hello Hello Hello Hello Hello 


    23. One-liner Python code to check for Anagram string.

    from collections import Counter
    
    
    str1 = "state"
    str2 = "taste"
    
    print(f"Are {str1} and {str2} Anagram?: ", Counter(str1)==Counter(str2))

    Output

    Are state and taste Anagram?:  True

    24. Transpose a matrix

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    transpose = list(zip(*matrix))
    
    print(transpose)

    Output

    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

    25. Merge the multiple dictionaries

    a = {'a':2, 'A':50}
    b = {'b':4, 'B':34}
    c = {'c':2, 'C':45}
    
    combine = {**a, **b, **c}
    
    print(combine)

    Output

    {'a': 2, 'A': 50, 'b': 4, 'B': 34, 'c': 2, 'C': 45}


    26. Initialize a list with the same elements.

    ones = [1]*100
    
    print(ones)
    

    Output

    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

    27. Insert different values inside a string

    a = 20
    
    b= 30
    
    c = [1, 2, 3]
    
    string = f'a: {a}, b: {b}, c: {c}'
    
    print(string)

    Output

    a: 20, b: 30, c: [1, 2, 3]

    28. Print the new value by replacing the old (carriage return in python)

    import time
    while(True):
      print(time.ctime(), end ="\r")  
      time.sleep(1)

    Output

    Sun Jan 29 19:24:51 2023

    29. Resolve the keyword name conflict

    Sometimes we wish to use an identifier name that has the same as the keyword. In such cases, we put a trailing underscore after the variable name so it does not conflict with the reserved keywords name.

    a=20
    b =40
    sum_ = a+b
    print(sum_)

    Output

    60

    30. What is __name__ == '__main__'

    When we execute a Python script directly, Python assigns a global default variable __name__ and sets its value to  ‘__main__’ for that script.
    If we do not execute a strict directly and import it into another python file, the value of __name__ is set to the script’s file name.

    Final Word

    Python is known for its beginner-friendly and clear syntax that emphasizes code readability by using indentation rather than semicolons and curly braces. The language construct of Python makes it easier for developers to write clear and logical code for small projects. We have covered some essential Python tips and tricks in this article that can help you write Python code quickly and efficiently. If you have any queries or suggestions, feel free to share them in the comments section below.

    Leave a Comment on this Post

    0 Comments