logo

... comprehensions: example



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

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



Solution
[c.upper() if c in 'aeuio' else c 
  for i, c in enumerate(old_list) 
  if i % 2 == 0]

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