Calmcode - comprehensions: enumerate

Enumerate

1 2 3 4 5 6 7 8 9

What's great about comprehensions is that they greatly simplify your code.

Let's show an example. The block of code below 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]