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

As an exercise, turn the code block below into a comprehensions.

old_list = 'abcde'
new_list = []
for i, c in enumerate(old_list):
    if i % 2 == 0:
        if c in 'aeuio':
            char = c.upper()
        else:
            char = c
        new_list.append(char)
new_list

Solution
[c.upper() if c in 'aeuio' else c 
  for i, c in enumerate(old_list) 
  if i % 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.