Member-only story
4 Tips to Improve Your Python Code
Assign multiple items, improve your conditionals, and more!
Python is a great programming language that makes it easy to up and running. There are many hidden gems in the language that make it even easier to use.
The tips listed below not only make your code easier to read, but also make your code safer to run. You’ll encounter less crashes and fewer redundancies in your code, meaning there’ll be less to maintain.
1. Assign Multiple Items Directly
One of the amazing features available in Python is the ability to assign multiple items directly. Multiple assignments is a feature that’s often under-utilized by many Python programmers, but it can really speed up your workflow.
The term multiple assignments can often be used interchangeably with tuples unpacking of iterable unpacking.
Let’s see how we can assignment multiple items directly:
One of the great things about this is that this also works for unpacking iterable items, such as lists or tuples.
Let’s see how we can assign parts of lists to different variables:
An important thing to note here is that the number of variables should be the same.
For example, if you wrote a, b = [1,2,3]
, then this would throw a ValueError
. The reason for this is that there is a mismatch between the two sides of the assignment.
To work around this, you can unpack the remaining values using the *
operator: