20 Python Snippets You Should Learn Today

Some tips and tricks to help you code faster

Chaitanya Baweja
Oct 8, 2019 · 4 min read
Photo by Chris Ried on Unsplash

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

As the Zen of Python says:

Beautiful is better than ugly.
Explicit is better than implicit.

This is why it is worthwhile to remember some common Python tricks to help improve your code design. These will save you the trouble of surfing Stack Overflow every time you need to do something.

The following tricks will prove handy in your day-to-day coding exercises.


1. Reversing a String

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

You can read more about this here.


2. 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.


3. Finding Unique Elements in a String

The following snippet can be used to find all the unique elements in a string. We use the property that all elements in a set are unique.


4. 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.

An interesting use case of this could be 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 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.

You can read more about it here.


6. Swap Values Between Two Variables

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


7. 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.


8. 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.


9. Check If a Given String Is a Palindrome or Not

We have already discussed how to reverse a string. So palindromes become a straightforward program in Python.


10. Frequency of Elements in a List

There are multiple ways of doing this, but my favorite is using the Python Counter class.

Python counter keeps track of the frequency of each element in the container. Counter() returns a dictionary with elements as keys and frequency as values.

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


11. Find Whether Two Strings are Anagrams

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

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase.

If the Counter objects of two strings are equal, then they are anagrams.


12. 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.


13. Using Enumerate to Get Index/Value Pairs

The following script uses enumerate to iterate through values in a list along with their indices.


14. Check the Memory Usage of an Object

The following script can be used to check the memory usage of an object. Read more about it here.


15. Merging Two Dictionaries

While in Python 2, we used the update() method to merge two dictionaries; Python 3.5 made the process even simpler.

In the script given below, two dictionaries are merged. Values from the second dictionary are used in case of intersections.


16. Time Taken to Execute a Piece of Code

The following snippet uses the time library to calculate the time taken to execute a piece of code.

17. Flattening a List of Lists

Sometimes you’re not sure about the nesting depth of your list, and you simply want all the elements in a single flat list.

Here’s how you can get that:

Numpy flatten is a better way to do this if you have a properly formatted array.


18. Sampling From a List

The following snippet generates n number of random samples from a given list using the random library.

I have been recommended the secrets library for generating random samples for cryptography purposes. The following snippet will work only on Python 3.


19. Digitize

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


20. Check for Uniqueness

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


Conclusion

These were some short snippets I find extremely useful in my everyday work. 30 seconds of python helped a lot while researching for this story.

Thank you for reading this story. Hope you enjoyed it.

Better Programming

Advice for programmers.

Chaitanya Baweja

Written by

Machine Learning Engineer | Python | Data Analytics | Economics | Physics

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Fun Side Projects That You Can Build Today

3K

More from Better Programming

More from Better Programming

The Zero-Dollar Infrastructure Stack

1.1K

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade