logo

... comprehensions: enumerate



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 signing up for the newsletter.