Python is one of the widely used Programming languages today with applications in various fields, such as data science, scientific computing, web dev, game dev, and building desktop graphical interfaces. Python gained this popularity for its usefulness in various fields, how productive it is compared to other programming languages like Java, C, and C++, and English-like its commands are.
Suppose you’re new to data science or programming in general. In that case, you often find people recommending Python as the first programming language to learn because it has a simple-to-understand syntax and better code readability, making learning much more straightforward for individuals with no prior programming backgrounds.
When you use Python every day to solve challenges, develop algorithms and build applications, you will find yourself repeating some tasks over and over again. That’s why it is an excellent option to have some code snippets for the usually performed tasks, so you can use them straight ahead in your project whenever you need them.
I know that there are many snippets out there for Python categorized by field. For example, there are Python snippets, especially for data science, or for exploratory data analysis or visualization. Besides data science, there are snippets for game dev, graphical interface design, and web dev. But, for this article, I will focus on general-purpose snippets that you can use for all these applications.
Lists Snippets
We will start with a few snippets about what I would argue, Python’s most used data structure, lists.
№1: Merge two lists into a Dictionary
Assume we have two lists in Python, and we want to merge them in a dictionary form, where one list’s items act as the dictionary’s keys and the other’s as the values. This is a very frequent problem often faced when writing code in Python.
But to solve this problem, we need to consider a couple of restrictions, such as the sizes of the two lists, the types of items in the two lists, and if there are any repeated items in them, especially in the one we will use as keys. We can overcome that with the use of built-in functions like zip
.
№2: Merge two or more lists into a list of lists
Another frequent task is when we have two or more lists, and we want to collect them all in one big list of lists, where all the first items of the smaller list form the first list in the bigger list.
For example, if I have 4 lists [1,2,3]
, ['a','b','c']
, ['h','e','y']
, and [4,5,6]
and we want to make a new list of those four lists; it will be [[1,'a','h',4], [2,'b','e',5], [3,'c','y',6]]
.
№3: Sort a list of dictionaries
The next set of everyday list tasks is sorting tasks. Depending on the data type of the items included in the lists, we will follow a slightly different way to sort them. Let’s first start with sorting a list of dictionaries.
№4: Sort a list of strings
We are often faced with lists containing strings, and we need to sort those lists alphabetically, by length or any other factor we want or our application needs.
Now, I should mention that these are straightforward ways to sort a list of strings, but you may sometimes need to implement your sorting algorithm to solve that problem.
№5: Sort a list based on another list
Sometimes, we may want/ need to use one list to sort another. So, we will have a list of numbers (the indexes) and a list that I want to sort using these indexes.
№6: Map a list into a dictionary
The last list-related task we will address in this article is if we are given a list and map it into a dictionary. That is, I want to convert my list into a dictionary with numerical keys.
Dictionary Snippets
The following data type we will address is dictionaries.
№7: Merging two or more dictionaries
Assume we have two or more dictionaries, and we want to merge them all into one dictionary with unique keys.
https://gist.github.com/SaraM92/86da0ae9383f493ad5680c8f3021c039
№8: Inverting a dictionary
One very common dictionary task is if we have a dictionary and want to flip its keys and values. So, the keys will become the values, and the values will become the keys.
When we do that, we need to make sure that I don’t have duplicate keys, values can be repeated, but keys can not, and make sure that all the new keys are hashable.
String Snippets
№9: Using f strings
Formatting a string is probably the number 1 task you will need to do almost daily. There are various ways you can format strings in Python; my favorite one is using f strings.
№10: Checking for Substrings
One of the very common tasks that I needed to perform many times before was to check if a string was in a list of strings.
№11: Get string’s size in bytes
Sometimes, especially when building memory-critical applications, we need to know how much of the memory our strings are using. Luckily, this can be done very quickly with one line of code.
Input/ Output operations
№12: Checking if a file exists
We often need to read data from files or write data to them in data science and many other applications. But to do that, we need to check if a file exists or not. So, our code doesn’t terminate with an error.
№13: Parsing a spreadsheet
Another very common file interaction is parsing data from a spreadsheet. Luckily, we have the CSV module to help us perform that task efficiently.
Takeaways
As a computer science instructor, I meet many people from different age groups that want to learn to program. They usually come to me with a programming language in mind or an application field they want to get into. My younger students often just want to learn to code, while older students want to get into a specific area like data science or web dev.
When I teach programming, I like to make things simple, and one of the successful tactics I found out is, if I teach people how to do the basics and build some building blocks, they will be able to develop more significant projects using these building blocks. That’s when I started collecting useful Python code snippets to share with my students and use myself in my work.
In this article, we walked together through 13 of these code snippets that you can add to your snippets database, or start a new one. These snippets are simple, short, and efficient and you will end up using at least one of them in any Python project regardless of which application field you’re working in. So I hope you find them helpful.