logo

... comprehensions.


Python has a system that might simplify your code called comprehensions. They allow you to turn your nested for loop into an amazing single line of code. In this series of videos we'll highlight some useful ways to use them.


Notes

Dictionaries have an .items() method that offers a lot of freedom.

d = {'a': 1, 'b': 2, 'c': 3}
[(k, v) for k, v in d.items()]

Using .items() you can have access to both the keys and the values. You could use it, for example, to quickly double all the values in a dictionary;

d = {'a':1, 'b':2}
{k: v * 2 for k, v in d.items()}

Another function to be aware of is zip. It allows you to "zip" lists together like a zipper.

[(a, b) for a, b in zip([1, 2, 3], [4, 5, 6])]

You can also zip three arrays together.

[(a, b, c) for a, b, c in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]

Feedback? See an issue? Something unclear? Feel free to mention it here.

If you want to be kept up to date, consider getting the newsletter.