Category Python

List Comprehensions in Python

to do list

Sometimes we want to do some very simple operations over the items of a list. Instead of using the same old way of iterating through lists, we can make our code simpler by using list comprehensions. Basic syntax To use…

Using chained comparison operators in Python

chain

In Python, there are the usual comparison operators: <, <=, >, >=, ==, !=. But one thing Python allows you to do that is not so common is chaining comparison operators more succinctly. Consider the example below using a well-known…

2 ways to merge Python dictionaries

Sea meets land

There are basically two ways of merging two or more dictionaries in Python. If you search randomly on the internet, you may find other approaches, but they are either inefficient computation-wise or just bad practices. How to do it before…

Understanding Slicing in Python

slice

Slicing is one of the most useful tools in the Python language. As such, it is important to have a good grasp of how it works. Basic Notation Let’s say we have an array called ‘list’. list[start:stop:step] start: where you…

Python Dictionary: a quick reference

how to python

The dictionary doesn’t guarantee the order of the elements and is mutable. One important characteristic of dictionaries is that you can set your customized access keys for each element. Initialization of a Dictionary Empty Dictionary people = {} Dictionary with…

Parse JSON in Python

In this tutorial, you will learn how to read JSON formatted strings, read JSON files as well as write in files and convert JSON objects into Python objects. A very common task performed by many programmers is parsing JSON –…

Python Ternary Operator

Computer screen with code

The ternary operator is a one-line if statement. Very handy for simple conditions. This is how it looks: <expression> if <condition> else <expression> Consider the following Python code: a = 25 b = 50 x = 0 y = 1…