Write an article or Share a link

10 useful Python Snippets every developer Should Learn

Hints Staff
3 months ago
10 useful Python Snippets every developer Should Learn by html hints

Python is a no-BS programming language. Readability and simplicity of design are two of the biggest reasons for its immense popularity.

The following snippets/tricks will help for Everyday Problems you face while coding in Python.


Reversing a String

The following snippet reverses a string using the Python slicing operation.

    # Reversing a string using slicing

    my_string = "ABCDE"
    reversed_string = my_string[::-1]


    # Output
    # EDCBA

Using rhe Title Case (First Letter Caps)

The following snippet can be used to convert a string to title case. This is done using the title() method of the string class.

    my_string = "my name is chaitanya baweja"

    # using the title() function of string class
    new_string = my_string.title()


    # Output
    # My Name Is Chaitanya Baweja

Printing a String or a List n Times

You can use multiplication (*) with strings or lists. This allows us to multiply them as many times as we like.

    n = 3 # number of repetitions

    my_string = "abcd"
    my_list = [1,2,3]

    # abcdabcdabcd

    # [1,2,3,1,2,3,1,2,3]

List Comprehension

List comprehension provides us with an elegant way of creating lists based on other lists.

The following snippet creates a new list by multiplying each element of the old list by two.

    # Multiplying each element in a list by 2

    original_list = [1,2,3,4]

    new_list = [2*x for x in original_list]

    # [2,4,6,8]

Swap Values Between Two Variables

Python makes it quite simple to swap values between two variables without using another variable.

    a = 1
    b = 2

    a, b = b, a

    print(a) # 2
    print(b) # 1

Split a String Into a List of Substrings

We can split a string into a list of substrings using the .split() method in the string class. You can also pass as an argument the separator on which you wish to split.

    string_1 = "My name is Chaitanya Baweja"
    string_2 = "sample/ string 2"

    # default separator ' '
    # ['My', 'name', 'is', 'Chaitanya', 'Baweja']

    # defining separator as '/'
    # ['sample', ' string 2']

Combining a List of Strings Into a Single String

The join() method combines a list of strings passed as an argument into a single string. In our case, we separate them using the comma separator.

    list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

    # Using join with the comma separator

    # Output
    # My,name,is,Chaitanya,Baweja

Using the try-except-else Block

Error handling in Python can be done easily using the try/except block. Adding an else statement to this block might be useful. It’s run when there is no exception raised in the try block.

If you need to run something irrespective of exception, use finally.

    a, b = 1,0

        # exception raised when b is 0
    except ZeroDivisionError:
        print("division by zero")
        print("no exceptions raised")
        print("Run this always")

Check the Memory Usage of an Object

The following script can be used to check the memory usage of an object.

    import sys

    num = 21


    # In Python 2, 24
    # In Python 3, 28


The following snippet will convert an integer into a list of digits.

    num = 123456

    # using map
    list_of_digits = list(map(int, str(num)))

    # [1, 2, 3, 4, 5, 6]

    # using list comprehension
    list_of_digits = [int(x) for x in str(num)]

    # [1, 2, 3, 4, 5, 6]

    # Even simpler approach
    list_of_digits = list(str(num))

    # [1, 2, 3, 4, 5, 6]

Check more at Code Perfect Plus


We use cookies to ensure better User Experience. Read More