Python tips

Raw Formatted Strings

PEP 498 and Python 3.6 introduced so-called formatted strings or f-strings. You can embed expressions inside such strings. It’s possible and straightforward to treat a string as both raw and formatted. You need to include both prefixes: fr.

Sort Dictionaries

You can use a similar approach to sort key-value tuples of dictionaries obtained with .items() method: They are sorted according to the keys. If you want to them to be sorted according to their values, you should specify the arguments that correspond to key and eventually reverse:

Sort Sequences

Sequences are sorted by their first elements by default: However, if you want to sort them according to their second (or other) elements, you can use the parameter key and an appropriate lambda function as the corresponding argument: It’s similar if you want to obtain the reversed order:

Unique Values

You can remove duplicates from a list, that is obtained unique values by converting it to a set if the order of elements is not important:

Transpose Matrices

Although people usually apply NumPy (or similar libraries) when working with matrices, you can obtain the transpose of a matrix with zip:

Aggregate Elements

If you’re going to aggregate the elements from several sequences, you should use zip: You can iterate through the obtained zip object or transform it into a list or tuple.

Reversed Iteration

If you want to iterate through a sequence in the reversed order, you should use reversed:

Advance Iteration

If you want to iterate through a sequence and you need both sequence elements and the corresponding indices, you should use enumerate: In each iteration, you’ll get a tuple with the index and corresponding element of the sequence.

Join Strings

If you need to join multiple strings, eventually having the same character or group of characters between them, you can use str.join() method:

Merge Dictionaries

One way to merge two or more dictionaries is by unpacking them in a new dict: