20 easy-to-use Python code snippets! ! ! (Python tips)

Python is a non-BS programming language. Design simplicity and legibility are two reasons for its popularity. Just like the tenet of Python: beautiful is better than ugly, and explicit is better than implicit.

It is useful to remember some common tips to help improve code design. In a pinch, these little tricks can save you the hassle of checking Stack Overflow online. And they’ll help you in your daily programming exercises.

1. Reverse a string

The following code uses the Python slice operation to reverse a string.


\# Reversing a string using slicing

  

my\_string = "ABCDE"

reversed\_string = my\_string\[::-1\]

  

print(reversed\_string)

  

\# Output

\#EDCBA


2. Use title classes (capitalized)

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



my\_string = "my name is chaitanya baweja"

  

\# using the title() function of string class

new\_string = my\_string. title()

  

print(new\_string)

  

\# Output

\# My Name Is Chaitanya Baweja


3. Find unique elements of a string

The following code can be used to find all unique elements in a string. We use its attribute, where all elements in a set of strings are unique.



my\_string = "aavvccccddddeee"

  

\# converting the string to a set

temp\_set = set(my\_string)

  

\# stitching set into a string using join

new\_string = .join(temp\_set)

  

print(new\_string)


4. Output n times a string or list

You can use multiply (*) on strings or lists. In this way, they can be multiplied as many times as desired.



n = 3 # number of repetitions

  

my\_string = "abcd"

my\_list = \[1,2,3\]

  

print(my\_string\*n)

\# abcdabcdabcd

  

print(my\_list\*n)

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

import stream lit as st



An interesting use case is to define a list with a constant value, let’s say zero.



n = 4

my\_list = \[0\]\*n # n denotes the length of the required list

\# \[0, 0, 0, 0\]


5. List comprehension

List comprehensions provide an elegant way to create lists based on other lists.

The following code creates a new list by multiplying each object of the old list twice.



\# Multiplying each element in a list by 2

  

original\_list = \[1,2,3,4\]

  

new\_list = \[2\*x for x in original\_list\]

  

print(new\_list)

\# \[2,4,6,8\]


6. Swap values between two variables

Python makes it very easy to swap values between two variables without using a third variable.



a = 1

b = 2

  

a, b = b, a

  

print(a) # 2

print(b) # 1


7. Split a string into a list of substrings

A string can be split into a list of substrings by using the .split() method. You can also pass the delimiter you want to split on as a parameter.



string\_1 = "My name is Chaitanya Baweja"

string\_2 = "sample/ string 2"

  

\# default separator

print(string\_1. split())

\# \[ My , name , is , Chaitanya , Baweja \]

  

\# defining separator as /

print(string\_2. split( / ))

\# \[ sample , string 2 \]


8. Combine a list of strings into a single string

The join() method combines a list of strings into a single string. In the example below, comma delimiters are used to separate them.



list\_of\_strings = \[ My , name , is , Chaitanya , Baweja \]

  

\# Using join with the comma separator

print( , .join(list\_of\_strings))

  

\# Output

\# My,name,is,Chaitanya,Baweja


9. Check if a given string is a palindrome

Reversing strings has been discussed above. Thus, a palindrome becomes a simple program in Python.



my\_string = "abcba"

  

m if my\_string == my\_string\[::-1\]:

    print("palindrome")

else:

    print("not palindrome")

  

\# Output

\# palindrome


10. Feature frequency for lists

There are several ways to accomplish this task, but my favorite is Python’s Counter class. A Python counter keeps track of the frequency of each element, and Counter() returns a dictionary where the elements are the keys and the frequencies are the values.

Also use the most_common() function to get the most_frequent element in the list.



\# finding frequency of each element in a list

from collections import Counter

  

my\_list = \[ a , a , b , b , b , c , d , d , d , d , d \]

count = Counter(my\_list) # defining a counter object

  

print(count) # Of all elements

\# Counter({<!-- --> d : 5, b : 3, a : 2, c : 1})

  

print(count\[ b \]) # of individual element

\# 3

  

print(count.most\_common(1)) # most frequent element

\# \[( d , 5)\]


11. Find if two strings are anagrams

An interesting application of the Counter class is to find anagrams.

Anagrams are new words or phrases formed by rearranging the letters of different words or phrases.

Two strings are anagrams if their counter objects are equal.



From collections import Counter

  

str\_1, str\_2, str\_3 = "acbde", "abced", "abcda"

cnt\_1, cnt\_2, cnt\_3 = Counter(str\_1), Counter(str\_2), Counter(str\_3)

  

if cnt\_1 == cnt\_2:

    print( 1 and 2 anagrams )

if cnt\_1 == cnt\_3:

    print( 1 and 3 anagram )


12. Use try-except-else blocks

Error handling in Python is easily solved by using try/except blocks. It might be useful to add an else statement in that block. When there is no exception in the try block, it runs normally.

If you want to run some program, use finally without considering exceptions.



a,b = 1,0

  

try:

    print(a/b)

    # exception raised when b is 0

except ZeroDivisionError:

    print("division by zero")

else:

    print("no exceptions raised")

finally:

    print("Run this always")


13. Use enumeration to get index and value pairs

The following script uses enumeration to iterate over the values and their indices in a list.



my\_list = \[ a , b , c , d , e \]

  

for index, value in enumerate(my\_list):

    print( {<!-- -->0}: {<!-- -->1} .format(index, value))

  

\# 0: a

\# 1: b

\# 2: c

\# 3: d

\# 4: e


14. Check memory usage of objects

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



import sys

  

num = 21

  

print(sys. getsizeof(num))

  

\# In Python 2, 24

\# In Python 3, 28


15. Merge two dictionaries

In Python 2, use the update() method to merge two dictionaries, and Python 3.5 makes the process easier.

In the given script, two dictionaries are merged. We use the values from the second dictionary so that there are no crossovers.



dict\_1 = {<!-- --> apple : 9, banana : 6}

dict\_2 = {<!-- --> banana : 4, orange : 8}

  

combined\_dict = {<!-- -->\*\*dict\_1, \*\*dict\_2}

  

print(combined\_dict)

\# Output

\# {<!-- --> apple : 9, banana : 4, orange : 8}


16. Time required to execute a piece of code

The code below calculates the time taken to execute a piece of code using the time library.



import time

  

start\_time = time. time()

\# Code to check follows

a,b = 1,2

c = a + b

\# Code to check ends

end\_time = time. time()

time\_taken\_in\_micro = (end\_time-start\_time)\*(10\*\*6)

  

print("Time taken in micro\_seconds: {0} ms"). format(time\_taken\_in\_micro)


17. List list flattening

Sometimes you’re not sure how deep your lists can be nested, and you just want all the elements in a single flat list.

It can be obtained by:



from iteration\_utilities import deepflatten

  

\# if you only have one depth nested\_list, use this

def flatten(l):

  return \[item for sublist in l for item in sublist\]

  

l = \[\[1,2,3\],\[3\]\]

print(flatten(l))

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

  

\# if you don't know how deep the list is nested

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

  

print(list(deepflatten(l, depth=3)))

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


Numpy flattening is a better choice if you have properly formatted arrays.

18. List sampling

Using the random software library, the following code generates n random samples from a given list.



import random

  

my\_list = \[ a , b , c , d , e \]

num\_samples = 2

  

samples = random.sample(my\_list,num\_samples)

print(samples)

\# \[ a , e \] this will have any 2 random values


It is highly recommended to use the secrets library to generate random samples for encryption.

The code below is for Python 3 only.



import secrets # imports secure module.

secure\_random = secrets. SystemRandom() # creates a secure random object.

  

my\_list = \[ a , b , c , d , e \]

num\_samples = 2

  

samples = secure\_random. sample(my\_list, num\_samples)

  

print(samples)

\# \[ e , d \] this will have any 2 random values


19. Digitization

The following code converts an integer to a list of numbers.



num = 123456

  

\# using map

list\_of\_digits = list(map(int, str(num)))

  

print(list\_of\_digits)

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

  

\# using list comprehension

list\_of\_digits = \[int(x) for x in str(num)\]

  

print(list\_of\_digits)

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


20. Check for uniqueness

The following function will check if all elements in a list are unique.



def unique(l):

    if len(l)==len(set(l)):

        print("All elements are unique")

    else:

        print("List has duplicates")

  

unique(\[1,2,3,4\])

\# All elements are unique

  

unique(\[1,1,2,3\])

\# List has duplicates


-END-