Unearthing Hidden Gems: 5 Python Tricks You Should Use Often
Photo by Karen La?rk Boshoff: https://www.pexels.com/photo/diamonds-on-charcoal-in-close-up-8395024/

Unearthing Hidden Gems: 5 Python Tricks You Should Use Often

Python offers a wide range of features and functionalities that go beyond the basics. While many developers are familiar with common Python techniques, there are several other tricks that can significantly enhance your coding efficiency and productivity. In this article, we will explore five such hidden Python tricks that are worth incorporating into your coding arsenal.

1. Use List Comprehensions

Let's say you want to retrieve a list of even numbers from a list of numbers, it may be easy to just write a for loop like the one below. Even though the code will work just fine it is taking up too much space.

No alt text provided for this image

Instead of using a for loop, we can use list comprehensions. List comprehension provide a concise and elegant way to create lists based on existing iterables. Let's rewrite the above code using list comprehension.

No alt text provided for this image

By incorporating an if statement within a list comprehension, we have filtered the data on the fly with just one line of code. List comprehension allows us to write more compact and readable code while achieving the desired outcome.

2. Context Managers using the "with" Statement

The "with" statement in Python is not only useful for file handling but also allows you to manage resources and ensure proper clean-up. So instead of using the following code to handle files:

No alt text provided for this image

We can use the "with" statement to handle the file. By leveraging context managers, you can eliminate the need for explicit resource management (file closed) and make your code more concise and robust. Context managers simplify error handling, guarantee resource release, and enhance code readability. Here is how the code would look like if we use a context manager:

No alt text provided for this image

When we use the "with" statement, no need to manually close the file like we did in the previous example, it is handled by the context manager. This is considered a best practice because it ensures that the file is properly closed, even if an exception occurs during reading.

3. Enumerate for Iteration with Indices

Let's say we want to iterate over sequences and access both the elements and their corresponding indices, we can write something like this:

No alt text provided for this image

Instead of using this complicated code, we can use the "enumerate" function. It provides a convenient way to achieve this. This function returns an iterator of tuples, each containing the index and the corresponding element, allowing for easy tracking and manipulation of both values during iteration. Here is a modified code using the enumerate function.

No alt text provided for this image

4. Using defaultdict to count occurrences

Using defaultdict from the collections module simplifies the process of counting occurrences since it automatically handles the initialization of keys and provides a default value. Let's say we have a list of fruits and we want to count how many times each fruit appears in a list, here is how we can do it using defaultdict:

No alt text provided for this image

In the example above, we create a defaultdict named fruit_counts with an initial value of 0. Then, we iterate over the fruits list and use each item as a key to access the fruit_counts dictionary. If the key is encountered for the first time, the default value of 0 is returned and incremented by 1. If the key is already present, the existing value is incremented by 1.The output is a dictionary of fruits (keys) and how many times the appear in the list (values).

5. Underscore (_) for Ignoring Values:

Sometimes you may need to ignore certain values during unpacking or looping. In such cases, Python allows you to use an underscore (_) as a variable name. It acts as a placeholder for values that you don't intend to use. This helps improve code readability by signaling your intention to disregard specific values explicitly. Let's say you want to unpack a name and you want to ignore the middle name, you would assign underscore (_) for the middle name variable. See the code below:

No alt text provided for this image

Conclusion

Expanding your knowledge of Python beyond the basics can significantly enhance your programming capabilities and elevate your Python coding skills to new heights. Thank you for reading. Please share this?story?and?subscribe?to this newsletter if you are not yet a subscriber. You can also follow me on?LinkedIn.

.................................................................................................................................

No alt text provided for this image


Mohammad Hossain

Business Intelligence Specialist | Data Analyst | BI Consultant | Business Analyst | Data Scientist | Insight Analyst | Power BI Developer | Business Intelligence Analyst |

1 年

print(list(range(0, 6, 2)))

Anton Ryazantsev

Sr. Software Developer | Expert Software Developer in Test | Python Mentor

1 年

Case 4 can be solved a bit simpler with another one feature "Counter" from collections: >>> from collections import Counter >>> fruits = ["apple", "banana", "apple", "orange", "banana"] >>> >>> print(Counter(fruits)) Counter({'apple': 2, 'banana': 2, 'orange': 1})

Syed Ahmed

Diploma in IT Advanced Networking and Cloud Engineering | AWS Certified Cloud Practitioner | Student at TAFE QLD | ISC2 CC

1 年

Hi, first example could reduce to further with the following example. Thanks ?? print([num for num in range(6) if num % 2 == 0])

Jakub Korus

Informatics & Economics (I&E) Student @ Leiden

1 年

Useful reminder of better practices!

要查看或添加评论,请登录

Benjamin Bennett Alexander的更多文章

社区洞察

其他会员也浏览了