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

This block of code is verbose.

old_list = 'abcde'
new_list = []
for i in range(len(old_list)):
    if i % 2 == 0:
        new_list.append(old_list[i])
new_list

It can be turned into a one-liner by using a comprehensions and the enumerate function.

[char for idx, char in enumerate('abcde') if idx % 2 == 0]

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.