Category: Code Mastery

Improving your code with container methods

Improving your code with container methods

In this article we will take a look at how you can implement a number of methods in your classes that will improve the readability of your code and make it easier to use code you have written. The methods in this post are usable when your code implements some sort of containers.

Improving your code readability with namedtuples

Improving your code readability with namedtuples

If you’ve programmed in Python for some time you’ve no doubt used to tuples to move around data in your code. Tuples are a very useful way of grouping related data in a single variable. One issue that often comes up with tuples is that they are very easy to abuse…

String formatting like a pro

String formatting like a pro

Just about every Python programmer has used the ‘%’ operator for string formatting. But another formatting method is available using the .format()  method of the string object. This allows for much cleaner and more readable code than the incantations written using ‘%’ operators.

Dictionary creation using dict comprehensions

Dictionary creation using dict comprehensions

In a previous Pythonic post we saw list comprehensions, an efficient Pythonic way to create lists.  I hope you got hooked and started using list comprehensions where your code could benefit from them. Similar to list comprehensions, Python has a similar feature that’s applicable to dictionaries. The fancy name? Yes, dictionary comprehensions or dict comprehenions. …

+ Read More

Enumerate your iterables!

Enumerate your iterables!

Whenever you write code similar to the following:

you should consider making your code a bit more Python by using the builtin enumerate  function:

The enumerate  function takes an iterable and an optional parameter start  (defaulting to 0). The return value is a tuple containing the index of the element and the element …

+ Read More

Build your lists using list comprehensions

Build your lists using list comprehensions

A common way to build lists in a program that we see is this construct

The basic construct here is that by looping over something (an iterable or a condition) we add items to our list. I’m sure you’ve been there and have already used this construct in some of your code. There is …

+ Read More