Five Python Tricks I Dare You to Know
The more you know, the more you know you don't know.”~ Aristotle
One of the most common wishes when one is writing Python code is wishing that there was a better way to achieve a specific task. For example, when your text is too long, you wish there was a way you could wrap it. If you have multiple values to return from a function, you wish there was a better and more structured way to return those values. And guess what? Sometimes there is a better way to do it; you just don't know about it. In this article, I want to talk about five Python tricks and tips that you have to know to improve your coding experience with Python. Let's get started.
1. Returning Multiple Values From a Function Using Namedtuples
By default, a function returns one value, and it stops the execution of the function. There are various ways you can return multiple values. If you want to return multiple values in a defined manner, you can use the namedtuple from the collections module. This will help you define the structure of the values that will be returned. In the code below, we create a namedtuple and assign fields: name, age, and car. We then assign values to these fields. This makes the values returned more defined.
One of the benefits of using namedtuple is that, like regular tuples, namedtuple instances are immutable, which ensures that the data cannot be modified accidentally.
2. Add and Pop Elements From Both Sides of a List
If you want to add and pop elements from both sides of a list, you can use deque (double-ended queue) . Unlike a normal list that lets you add and remove elements from one end, deque allows you to add and remove elements from both the left and right sides of the list. This makes it quite handy if one has a big stack. Deque is found in the collections module. In the example below, see how we are able to append elements at both ends of the list.
Deque also makes it easy to pop (remove) elements on both ends of the list. See the example below:
You can see that both 1 and 6 have been popped. So, deque is efficient for operations for appending and popping from both ends, making it an ideal choice for implementing queues and other data structures that require such operations.
[FINAL CALL] Build the Confidence to Tackle Data Analysis Projects (SUMMER 40% OFF)
Ready to go in and do some real data analysis? The main purpose of this book is to ensure that you develop data analysis skills with Python by tackling challenges. By the end, you should be confident enough to take on any data analysis project with Python. Start your 50-day challenge now. Click here to get 40% off.
Other Resources
Want to learn Python fundamentals the easy way? Check out Master Python Fundamentals: The Ultimate Guide for Beginners.
Challenge yourself with Python challenges. Check out 50 Days of Python: A Challenge a Day. (40% OFF)
100 Python Tips and Tricks, Python Tips and Tricks: A Collection of 100 Basic & Intermediate Tips & Tricks.
3. Checking if a String Contains Only Whitespaces
You can use the isspace() string method to check if a given string contains only whitespaces. This method checks if a string contains only whitespace (spaces, tabs, newlines, etc.). If it does, it returns a True value. Now, a string with whitespace is not an empty string. Using this method, an empty string will be evaluated as False since it has no white spaces. See the example below:
领英推荐
The isspace() method will return False if the string contains any characters other than whitespace characters. It only returns True if all characters in the string are whitespace characters and there is at least one whitespace character. See below:
Here, we get 'This string has no whitespaces' because the string contains non-whitespace characters (e.g., "Hello"). You can use this method for data analysis operations that require catching strings with all whitespaces.
4. Wrapping and Dedenting Text
If you have long text, you can use the wrap function from the textwrap library to wrap it. This function takes two arguments: the text you want to wrap and the length of each line. Below, we have a long text and we want to wrap it (that is, break it into two lines). The maximum length of each line will be 30 characters.
You can see that the long string has been wrapped into two strings.
If you have text that has some leading whitespace, you can remove it using textwrap.dedent(). This will remove any leading whitespace from every line in the input text Below, we have text that has indented lines. We are going to use dedent() on the text. We will print the text before using the dedent() function and after using it.
5. Creating a List that Holds Specific Data Type with Arrays
In Python, data structures like lists can hold arbitrary data types. However, you can create a list that can hold only one data type. This can be done using the arrays module. This module allows you to create and manipulate arrays in a more memory-efficient way when dealing with homogeneous data types.
When creating an array, you are to specify the type of data that it will hold. Below, we create an array that will hold only integer data types. The "i" represents the data type for integers.
Here we have created an array that is just like a list but can only hold one data type: integers. If we try to add another data type other than an integer to this array, it will generate a type error.
We can also create an array that holds only floating-point numbers. The 'f' represents the data type code for floating-point numbers:
Arrays can use list methods such as append, extend, copy, etc. Arrays are generally more memory-efficient than lists when you have a large number of elements of the same data type. This is because arrays store elements in a more compact manner without the need for additional type information for each element.
Conclusion
So, you can see that Python is full of functions and modules that can greatly improve your coding experience. If any of these tips sound new to you, well, it is because you have not read, "Python Tips and Tricks: A Collection of 100 Basic & Intermediate Tips & Tricks." This book has many cool tips and tricks that will greatly improve your Python knowledge. Thanks for reading.
Newsletter Sponsorship
You can reach a highly engaged audience of over 290,000 tech-savvy subscribers and grow your brand with a newsletter sponsorship. Contact me at [email protected] today to learn more about the sponsorship opportunities.
--
6 个月Educational ??
--???? ???? ??? ?????
7 个月Hi very good????????????
Data Engineer at IOTA Analytics
7 个月Request you to please share more & more informative tricks like this in the future too...
--???? ???? ??? ?????
7 个月It's great wow
--???? ???? ??? ?????
7 个月Very well